a
    Fb                     @   sN  d Z ddgZddlZddlZddlmZ ddlZddlZddlZddlm	Z	 ddl
Z
ddlZddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z! ddl"m#Z#m$Z$m%Z% ddl&m'Z' ddl(m)Z) ddl*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1 dd Z2e
j3j4j Z5e6j7j Z8dd e
j9e
j:e
j3e;fD Z<e=e>Z?e=e@jAZBe#ZCejDZEg dZFdd  ZGd!d" ZHee@df d#d$d%ZId;ee@df d#d'd(ZJd)d* ZKe+d+d, ZLe+d-d. ZMe+d<d0d1ZNd2d3 ZOe@d#d4d5ZPd6d7 ZQG d8d de)ZRe@d#d9d:ZSdS )=zTools for inspecting Python objects.

Uses syntax highlighting for presenting the various information elements.

Similar in spirit to the inspect module, but all calls take a name argument to
reference the name under which an object is being read.
	InspectorInspectColors    N)	signature)dedent)Union)page)pretty)skip_doctest)
PyColorize)openpy)	py3compat)safe_hasattr)compress_user)indent)list_namespace)typestr2type)
TermColorsColorSchemeColorSchemeTable)cast_unicode)	Colorable)undoc)	highlight)PythonLexer)HtmlFormatterc                 C   s   t | t tddS )NT)Z	noclasses)r   r   r   )code r   4lib/python3.9/site-packages/IPython/core/oinspect.pypylight1   s    r   c                 C   s   h | ]}t |qS r   )inspectgetdoc).0tr   r   r   	<setcomp>7   s   r#   )	type_name
base_classstring_form	namespacelengthfile
definition	docstringsourceinit_definitionclass_docstringinit_docstringcall_defcall_docstringismagicisaliasisclassfoundnamec                  K   s   dd t D }||  |S )z1Make an object info dict with all fields present.c                 S   s   i | ]
}|d qS Nr   )r!   kr   r   r   
<dictcomp>V       zobject_info.<locals>.<dictcomp>)info_fieldsupdate)kwZinfodictr   r   r   object_infoT   s    
r>   c                 C   sv   t | }|du rdS |dr"dS tj|s2dS t|d }t|j	\}}W d   n1 sd0    Y  |S dS )znGet encoding for python source file defining obj

    Returns None if obj is not defined in a sourcefile.
    Nz.soz.dllz.pydrb)
	find_fileendswithospathisfile	stdlib_ioopenr   detect_encodingreadline)objofilebufferencodinglinesr   r   r   get_encoding[   s    
.rO   returnc                 C   sB   z|   }W n ty   Y n0 t|tr4t|S t | }|S )a=  Stable wrapper around inspect.getdoc.

    This can't crash because of attribute problems.

    It also attempts to call a getdoc() method on the given object.  This
    allows objects which provide their docstrings via non-standard mechanisms
    (like Pyro proxies) to still be inspected by ipython's ? system.
    )r    	Exception
isinstancestrr   Zcleandoc)rJ   dsZdocstrr   r   r   r    r   s    



r     c                 C   s  t | trg }dD ]z}t| |}|durt|}|r<d| nd}|dd||f t|rt|tt	| q|d||t
|f  q|rd|S dS nnt| } zt	| }W nR ty   zt	| j}W n ttfy   Y Y dS 0 Y n ty
   Y dS 0 |S dS )al  Wrapper around inspect.getsource.

    This can be modified by other projects to provide customized source
    extraction.

    Parameters
    ----------
    obj : object
        an object whose source code we will attempt to extract
    oname : str
        (optional) a name under which the object is known

    Returns
    -------
    src : unicode or None

    )fgetfsetfdelNz%s.rV   z# z
%s%s = %s

)rS   propertygetattrrO   appendjoinr   
isfunctionr   	getsourcer   _get_wrapped	TypeError	__class__OSError)rJ   onameZsourcesattrnamefnrM   Zoname_prefixsrcr   r   r   r`      s6    



r`   c                 C   s(   t | p&t | p&t| tp&t| tS )zTrue if obj is a function ())r   r_   ZismethodrS   _builtin_func_type_builtin_meth_typerJ   r   r   r   is_simple_callable   s
    rl   c                 C   s2   t jdtdd t| dr(t| s(| j} t| S )zWrapper around :func:`inspect.getfullargspec`

    In addition to functions and methods, this can also handle objects with a
    ``__call__`` attribute.

    DEPRECATED: Deprecated since 7.10. Do not use, will be removed.
    z]`getargspec` function is deprecated as of IPython 7.10and will be removed in future versions.   
stacklevel__call__)warningswarnDeprecationWarningr   rl   rp   r   Zgetfullargspecrk   r   r   r   
getargspec   s    
rt   c                 C   s0   t jdtdd t| d | d | d | d S )a  Format argspect, convenience wrapper around inspect's.

    This takes a dict instead of ordered arguments and calls
    inspect.format_argspec with the arguments in the necessary order.

    DEPRECATED (since 7.10): Do not use; will be removed in future versions.
    za`format_argspec` function is deprecated as of IPython 7.10and will be removed in future versions.rm   rn   argsZvarargsZvarkwdefaults)rq   rr   rs   r   Zformatargspec)argspecr   r   r   format_argspec   s    
rx   Tc              	   C   s   t jdtdd | d}|du r(d}nTz|d d dk}W n ttfyR   Y n0 |rl|d d	d |d< | d
 t| }| d}|du r| d}|du r| dd}||fS )z?DEPRECATED since 6.0. Extract call tip data from an oinfo dict.zZ`call_tip` function is deprecated as of IPython 6.0and will be removed in future versions.rm   rn   rw   Nru   r   self   r6   r1   r/   r+   rV   )rq   rr   rs   getKeyError
IndexErrorrx   )ZoinfoZformat_callrw   Z	call_lineZhas_selfdocr   r   r   call_tip   s*    


r   c                 C   s2   | }d}t | dr.| j} |d7 }|dkr|S q| S )aN  Get the original object if wrapped in one or more @decorators

    Some objects automatically construct similar objects on any unrecognised
    attribute access (e.g. unittest.mock.call). To protect against infinite loops,
    this will arbitrarily cut off after 100 levels of obj.__wrapped__
    attribute access. --TK, Jan 2016
    r   __wrapped__rz   d   )r   r   )rJ   Zorig_objir   r   r   ra     s    
ra   c                 C   sn   t | } d}zt| }W nJ tyT   zt| j}W n ttfyN   Y n0 Y n tyd   Y n0 t|S )a^  Find the absolute path to the file where an object was defined.

    This is essentially a robust wrapper around `inspect.getabsfile`.

    Returns None if no file can be found.

    Parameters
    ----------
    obj : any Python object

    Returns
    -------
    fname : str
        The absolute path to the file where the object was defined.
    N)ra   r   Z
getabsfilerb   rc   rd   r   )rJ   fnamer   r   r   rA   #  s    
rA   c                 C   st   t | } zt| d }W nT ty\   zt| jd }W n ttfyV   Y Y dS 0 Y n tyn   Y dS 0 |S )aW  Find the line number in a file where an object was defined.

    This is essentially a robust wrapper around `inspect.getsourcelines`.

    Returns None if no file can be found.

    Parameters
    ----------
    obj : any Python object

    Returns
    -------
    lineno : int
        The line number where the object definition starts.
    rz   N)ra   r   Zgetsourcelinesrb   rc   rd   )rJ   linenor   r   r   find_source_linesF  s    r   c                       s   e Zd Zeejddddf fdd	Zd,eedf dddZ	edd	d
Z
dd Zdd Zd-ddZed.ddZd/ddZd0ddZd1eedddZdd Zd2ddZd3d d!Zd4d"d#Zd5edd$d%Zed&d' Zg d(d(fd(d)d*d+Z  ZS )6r   Nr   c                    sJ   t t| j||d || _tjd| |d| _| jj| _|| _| 	| d S )N)parentconfigrT   )outr   Zstyle)
superr   __init__color_tabler
   ZParserparserformatstr_detail_levelset_active_scheme)ry   r   Zcode_color_tableschemer   r   r   rc   r   r   r   g  s    
zInspector.__init__rV   rP   c                 C   s$   zt t||W S    Y dS 0 dS )zReturn the call signature for any callable object.

        If any exception is generated, None is returned instead and the
        exception is suppressed.N)_render_signaturer   )ry   rJ   re   r   r   r   _getdefs  s    zInspector._getdefc                 C   s   d| j jj|| j jjf S )z*Return a header string with proper colors.z%s%s%s)r   Zactive_colorsheaderZnormal)ry   hr   r   r   Z__head}  s    zInspector.__headc                 C   s&   |d ur"| j | | jj | d S r7   )r   r   r   )ry   r   r   r   r   r     s    zInspector.set_active_schemec                 C   s,   t d| dd |r"t d|  nt   dS )z-Generic message when no information is found.zNo %s found endzfor %sN)print)ry   msgre   r   r   r   noinfo  s    zInspector.noinfoc                 C   sf   t |std dS d}t|r,| d}| ||}|du rN| d| nt|| |dd dS )zwPrint the call signature for any callable object.

        If the object is a class, print the constructor information.zObject is not callable.NrV   zClass constructor information:
zdefinition headerr   r   )callabler   r   r4   _Inspector__headr   r   r   )ry   rJ   re   r   outputr   r   r   pdef  s    

zInspector.pdefc           	      C   s   | j }g }t|}|r&||d|}|rF||d |t| t|rt|drt|j}|dur||d |t| n4t|drt|j	}|r||d |t| |s| 
d| ntd	| dS )
a  Print the docstring for any object.

        Optional:
        -formatter: a function to run the docstring through for specially
        formatted docstrings.

        Examples
        --------
        In [1]: class NoInit:
           ...:     pass

        In [2]: class NoDoc:
           ...:     def __init__(self):
           ...:         pass

        In [3]: %pdoc NoDoc
        No documentation found for NoDoc

        In [4]: %pdoc NoInit
        No documentation found for NoInit

        In [5]: obj = NoInit()

        In [6]: %pdoc obj
        No documentation found for obj

        In [5]: obj2 = NoDoc()

        In [6]: %pdoc obj2
        No documentation found for obj2
        z
plain/textzClass docstring:r   NzInit docstring:rp   zCall docstring:ZdocumentationrZ   )r   r    r{   r]   r   r   r4   hasattrr   rp   r   r   r^   )	ry   rJ   re   	formatterheadrN   rU   init_dscall_dsr   r   r   pdoc  s*    "


zInspector.pdocc                 C   sZ   t   zt||d}W n ty.   d}Y n0 |du rF| d| nt| | dS )z$Print the source code for an object.)re   Nr,   )	linecache
checkcacher`   rR   r   r   r   )ry   rJ   re   rh   r   r   r   psource  s    
zInspector.psourcec                 C   s~   t |}|du r | d| dS t|}|dr@td|  n:tj|sZtd|  n t| 	t
j|dd|d  dS )	z0Show the whole file where an object was defined.Nr)   r?   z File %r is binary, not printing.z%File %r does not exist, not printing.F)Zskip_encoding_cookierz   )r   r   rA   rB   r   rC   rD   rE   r   r   r   Zread_py_file)ry   rJ   re   r   rK   r   r   r   pfile  s    
zInspector.pfile)textrQ   c                 C   sV   |d| d d}|du r|S ||}t |tsB|d| d dS t|fi |S dS )aF  Return a mime bundle representation of the input text.

        - if `formatter` is None, the returned mime bundle has
           a `text/plain` field, with the input text.
           a `text/html` field with a `<pre>` tag containing the input text.

        - if `formatter` is not None, it must be a callable transforming the
          input text into a mime bundle. Default values for `text/plain` and
          `text/html` representations are the ones described above.

        Note:

        Formatters returning strings are supported but this behavior is deprecated.

        z<pre>z</pre>
text/plain	text/htmlN)rS   dict)ry   r   r   rv   Z	formattedr   r   r   _mime_format  s    


zInspector._mime_formatc           
      C   s   |d }d}t t| \}}tdd |D }t||D ]P\}}|d}d|v rVdnd}	|| |d |t| d  |	 | d 7 }q8||d< |S )Nr   rV   c                 s   s   | ]}t |V  qd S r7   len)r!   r   r   r   r   	<genexpr>1  r:   z(Inspector.format_mime.<locals>.<genexpr>rZ   r   :)listzipmaxstripr   r   )
ry   bundleZ
text_plainr   ZheadsZbodies_lenr   bodyZdelimr   r   r   format_mime+  s    
0zInspector.format_mimer   c           
         s  j || |d g dd}d,ttd fdd}fdd	}	 d
 rZ||dd n d r|dkrz||dd|	 n||dd| ||dd nR d st|r(||dd|	 ||dd|	 ||dd| |dkr d r||dd|	 n||dd| ||dd ||dd ||dd n||dd|	 ||d d!|	 ||dd ||d"d  d# d$krv||d%d# ||d&d' ||dd |dkr d r||dd|	 n||dd| ||d(d)| ||dd| ||d*d+| |S )-a9  Retrieve an info dict and format it.

        Parameters
        ----------
        obj : any
            Object to inspect and return info from
        oname : str (default: ''):
            Name of the variable pointing to `obj`.
        formatter : callable
        info
            already computed information
        detail_level : integer
            Granularity of detail level, if set to 1, give more information.
        omit_sections : container[str]
            Titles or keys to omit from output (can be set, tuple, etc., anything supporting `in`)
        re   infodetail_levelrV   r   N)titlekeyc                    sn   |v s|v rd S  | }|d urj ||}| d ||d f | d  d| d |d  d 7  < d S )Nr   r   z<h1>z</h1>
rZ   )r   r]   )r   r   r   r   ZfieldZformatted_fieldr   omit_sectionsry   r   r   append_fieldV  s    z)Inspector._get_info.<locals>.append_fieldc                    s     | t| dS )Nr   )r   r   )r   )ry   r   r   code_formatter_  s    z+Inspector._get_info.<locals>.code_formatterr3   Reprr&   r2   r   ZSourcer,   Z	Docstringr+   ZFiler)   r4   Z	Signaturer*   zInit signaturer-   zInit docstringr/   Typer$   Z
Subclasses
subclasseszCall signaturer0   zString formr'   ZInteractiveZ	NamespaceZLengthr(   zClass docstringr.   zCall docstringr1   )N)r   rT   rl   r   )
ry   rJ   re   r   r   r   r   Z_mimer   r   r   r   r   	_get_info;  sL    	zInspector._get_infoTc                 C   s.   | j ||||||d}|s |d= t| dS )a   Show detailed information about an object.

        Optional arguments:

        - oname: name of the variable pointing to the object.

        - formatter: callable (optional)
              A special formatter for docstrings.

              The formatter is a callable that takes a string as an input
              and returns either a formatted string or a mime type bundle
              in the form of a dictionary.

              Although the support of custom formatter returning a string
              instead of a mime type bundle is deprecated.

        - info: a structure with some information fields which may have been
          precomputed already.

        - detail_level: if set to 1, more information is given.

        - omit_sections: set of section keys and titles to omit
        )r   r   N)r   r   )ry   rJ   re   r   r   r   Zenable_html_pagerr   r   r   r   pinfo  s    !zInspector.pinfoc                 C   s"   t jdtdd | j||||dS )z
        Inspector.info() was likely improperly marked as deprecated
        while only a parameter was deprecated. We "un-deprecate" it.
        zThe `Inspector.info()` method has been un-deprecated as of 8.0 and the `formatter=` keyword removed. `Inspector._info` is now an alias, and you can just call `.info()` directly.rm   rn   r   )rq   rr   rs   r   )ry   rJ   re   r   r   r   r   r   _info  s    zInspector._infoc                 C   s  |du rd}d}d}n|j }|j}|j}|rt|s`zd|d  }W q   dt| }Y q0 qdt| }|jr|d|j 7 }nt|}|du rd	}t|d
||dd}	d}
t|
d d }|rd|	d< n|rd|	d< nt	|j
|	d< z|j}t||	d< W n   Y n0 || jkrztt|}d}|st||
kr|d| d || d  }ddt|   dd |dD }||	|< W n   Y n0 |r||	d< ztt||	d< W n ty   Y n0 d}t|}|du rd
}n.|drd
}n|drd}t||	d< |rxt  z:t|ts<|s`t||}|durX| }||	d< W n tyv   Y n0 |r| |	d|s||	d < t|rd
|	d!< z| ||}W n t y   d}Y n0 z
|j!}W n t y   d}Y nH0 |du r,z| ||}W n t y*   Y n0 t|}|t"krBd}|rP||	d"< |r^||	d#< d$d% t	#|D }t|d&k rd'|}nd'|dd& d(g }||	d)< n| ||}|r||	d*< |rzt$|d+}W n   d}Y n
0 t|}|t%v rd}|r||kr||	d,< zt|j!}|t"kr8d}W n t yR   d}Y n0 |rb||	d#< t&|d-rt'|s| |j(|}|r||	d*kr||	d.< t|j(}|t)krd}|r||	d/< t*f i |	S )0a  Compute a dict with detailed information about an object.

        Parameters
        ----------
        obj : any
            An object to find information about
        oname : str (default: '')
            Name of the variable pointing to `obj`.
        info : (default: None)
            A struct (dict like with attr access) with some information fields
            which may have been precomputed already.
        detail_level : int (default:0)
            If set to 1, more information is given.

        Returns
        -------
        An object info dict with known fields from `info_fields`. Keys are
        strings, values are string or None.
        NFrV   z!Alias to the system command:
  %srz   zAlias: z	Alias to z
Docstring:
z<no docstring>T)r6   r5   r3   r2   r         rm   zMagic functionr$   zSystem aliasr%   r&   z <...> rZ   r   c                 s   s   | ]}|  V  qd S r7   )r   )r!   qr   r   r   r     r:   z!Inspector.info.<locals>.<genexpr>r'   r(   r?   z<string>z9Dynamically generated function. No source code available.r)   r,   r+   r4   r-   r/   c                 S   s   g | ]
}|j qS r   )__name__)r!   subr   r   r   
<listcomp>j  r:   z"Inspector.info.<locals>.<listcomp>
   , z...r   r*   rc   r.   rp   r0   r1   )+r2   r3   r'   r   rT   __doc__r    r   inttyper   rc   r   r   
expandtabsr^   splitrR   rA   rB   r   r   r   rS   r[   r`   rstrip_source_contains_docstringr{   r   r4   r   AttributeErrorr   _object_init_docstring__subclasses__r\   _builtin_type_docstringsr   rl   rp   _func_call_docstringr>   )ry   rJ   re   r   r   r2   r3   ZospacerU   r   Z
string_maxZshalfZbclassZostrZstr_headZbinary_filer   rh   Zinit_defZobj_initr   namesZ	all_namesZdeflnclsZclass_dsr0   r   r   r   r   r     s   
















zInspector.infoc                 C   s<   z"t t| j\}t ||kW S  ty6   Y dS 0 dS )z
        Check whether the source *src* contains the docstring *doc*.

        This is is helper function to skip displaying the docstring if the
        source already contains it, avoiding repetition of information.
        FN)astparser   r   Zget_docstringrR   )rh   r~   Zdef_noder   r   r   r     s
    z$Inspector._source_contains_docstringF)
list_typesc                C   s   d}d}|r$t  dtt dS | }	t|	}
|
dkrF|	d }n|
dkrX|	\}}ntd| |D ] }||vrhtd	|| f qht t  }}|D ]D}|| }t	||v rq|
t	| t|||||d
}|| qt  dt| dS )a  Search namespaces with wildcards for objects.

        Arguments:

        - pattern: string containing shell-like wildcards to use in namespace
          searches and optionally a type specification to narrow the search to
          objects of that type.

        - ns_table: dict of name->namespaces for search.

        Optional arguments:

          - ns_search: list of namespace names to include in search.

          - ignore_case(False): make the search case-insensitive.

          - show_all(False): show all names, including those starting with
            underscores.

          - list_types(False): list all available object types for object matching.
        allrV   rZ   Nrz   r   rm   z)invalid argument string for psearch: <%s>z'invalid namespace <%s>. Valid names: %s)ignore_caseshow_all)r   r^   sortedr   r   r   
ValueErrorkeyssetidaddr   r<   )ry   patternZns_tableZ	ns_searchr   r   r   Ztype_patternfilterZcmdsZlen_cmdsr6   Zsearch_resultZnamespaces_seenZns_namensZtmp_resr   r   r   psearch  s<    


zInspector.psearch)rV   )rV   )rV   N)rV   )rV   )N)rV   NNr   r   )rV   NNr   Tr   )rV   Nr   )rV   Nr   )r   
__module____qualname__r   r
   ANSICodeColorsr   r   rT   r   r   r   r   r   r	   r   r   r   r   r   r   r   r   r   r   staticmethodr   r   __classcell__r   r   r   r   r   e  sH   

9

& 
a      
(
 T
c                 C   s  g }d}d}| j  D ]f}|jtjkr,d}n|r>|d d}|jtjkrPd}n|jtjkrn|rn|d d}|t| q|r|d t	|t
dd |D  dkrd|d	d
d |D }nd|d|}| jtjurt| j}|d|7 }|S )z
    This was mostly taken from inspect.Signature.__str__.
    Look there for the comments.
    The only change is to add linebreaks when this gets too long.
    FT/*c                 s   s   | ]}t |d  V  qdS )rm   Nr   r!   rr   r   r   r     r:   z$_render_signature.<locals>.<genexpr>K   z{}(
{})rV   c                 s   s   | ]}d  |V  qdS )z    {},
N)r   r   r   r   r   r     s   z{}({})r   z -> {})
parametersvalueskindr   Z_POSITIONAL_ONLYr]   Z_VAR_POSITIONALZ_KEYWORD_ONLYrT   r   sumr   r^   Zreturn_annotationZ_emptyZformatannotation)Zobj_signatureZobj_nameresultZpos_onlyZkw_onlyZparamZrenderedZannor   r   r   r     s4    


r   )rV   )T)Tr   __all__r   r   r   r   rq   rC   textwrapr   typesiorF   typingr   ZIPython.corer   ZIPython.lib.prettyr   ZIPython.testing.skipdoctestr	   ZIPython.utilsr
   r   r   ZIPython.utils.dir2r   ZIPython.utils.pathr   ZIPython.utils.textr   ZIPython.utils.wildcardr   r   ZIPython.utils.coloransir   r   r   ZIPython.utils.py3compatr   ZIPython.utils.colorabler   ZIPython.utils.decoratorsr   Zpygmentsr   Zpygments.lexersr   Zpygments.formattersr   r   FunctionTyperp   r   objectr   r   
ModuleType
MethodTyper[   r   r   r   ri   rT   upperrj   ZColorsr   r   r;   r>   rO   r    r`   rl   rt   rx   r   ra   rA   r   r   r   r   r   r   r   <module>   s~   


<

%#     