
    f`                         d Z ddlZddlZddlZddlmZ ddlmZ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 e G d
 de
             Zy)z5Implementation of namespace-related magic functions.
    N)page)StdinNotImplementedError
UsageError)Magicsmagics_class
line_magic)skip_doctest)DEFAULT_ENCODING)read_py_file)get_py_filenamec                   "   e Zd ZdZedd       Zedd       Zeedd              Zedd       Z	edd       Z
edd       Zedd	       Zeedd
              Zeedd              Zeedd              Zedd       Zedd       Zedd       Zy)NamespaceMagicszMagics to manage various aspects of the user's namespace.

    These include listing variables, introspecting into them, etc.
    Nc                     d}t        j                  d|      j                         \  }}}}|s|s|rd}d|v r| j                  |       y| j                  j                  d|||       y)zpProvide detailed information about an object.

        '%pinfo object' is just a synonym for object? or ?object.r   z(pinfo )?(\?*)(.*?)(\??$)   *pinfodetail_level
namespacesN)rematchgroupspsearchshell_inspect)selfparameter_sr   r   r   qmark1onameqmark2s           X/var/www/cvtools/html/venv/lib/python3.12/site-packages/IPython/core/magics/namespace.pyr   zNamespaceMagics.pinfo(   so      xx4[AHHJ 	"fU6FfL%<LLJJ\+5   7    c                 B    | j                   j                  d|d|       y)zyProvide extra detailed information about an object.

        '%pinfo2 object' is just a synonym for object?? or ??object.r   r   r   Nr   r   r   r   r   s      r!   pinfo2zNamespaceMagics.pinfo2=   s$    
 	

G[q'1 	 	3r"   c                 >    | j                   j                  d||       y)a  Print the call signature for any callable object.

        If the object is a class, print the constructor information.

        Examples
        --------
        ::

          In [3]: %pdef urllib.urlopen
          urllib.urlopen(url, data=None, proxies=None)
        pdefNr$   r%   s      r!   r(   zNamespaceMagics.pdefE   s     	

F;
;r"   c                 >    | j                   j                  d||       y)zPrint the docstring for an object.

        If the given object is a class, it will print both the class and the
        constructor docstrings.pdocNr$   r%   s      r!   r*   zNamespaceMagics.pdocU   s     	

F;
;r"   c                 X    |st        d      | j                  j                  d||       y)z;Print (or run through pager) the source code for an object.zMissing object name.psourceN)r   r   r   r%   s      r!   r,   zNamespaceMagics.psource]   s)     344

Ik:>r"   c                    | j                   j                  d||      }|dk(  rF	 t        |      }t        j
                  | j                   j                  t        |d                   yy# t        $ r}t	        |       Y d}~yd}~ww xY w)a  Print (or run through pager) the file where an object is defined.

        The file opens at the line where the object definition begins. IPython
        will honor the environment variable PAGER if set, and otherwise will
        do its best to print the file in a convenient form.

        If the given argument is not an object currently defined, IPython will
        try to interpret it as a filename (automatically adding a .py extension
        if needed). You can thus use %pfile as a syntax highlighting code
        viewer.pfilez	not foundNF)skip_encoding_cookie)r   r   r   IOErrorprintr   
pycolorizer   )r   r   r   outfilenamemsgs         r!   r.   zNamespaceMagics.pfiled   sy     jj!!'+zB+*;7 IIdjj++LX],^_`   c
s   A* *	B3BBc                    g d}| j                  |dd      \  }}|j                  }| j                  }|j                  j                  }d}d|v rd}d|v rd}	nd|v rd}	n|j
                   }	|j                   |d	g               |d
g       x}
}
|D cg c]	  }||
vs| }}	  |||j                  | |d      |	|       yc c}w #  |j                          Y yxY w)az  Search for object in namespaces by wildcard.

        %psearch [options] PATTERN [OBJECT TYPE]

        Note: ? can be used as a synonym for %psearch, at the beginning or at
        the end: both a*? and ?a* are equivalent to '%psearch a*'.  Still, the
        rest of the command line must be unchanged (options come first), so
        for example the following forms are equivalent

        %psearch -i a* function
        -i a* function?
        ?-i a* function

        Arguments:

          PATTERN

          where PATTERN is a string containing * as a wildcard similar to its
          use in a shell.  The pattern is matched in all namespaces on the
          search path. By default objects starting with a single _ are not
          matched, many IPython generated objects have a single
          underscore. The default is case insensitive matching. Matching is
          also done on the attributes of objects and not only on the objects
          in a module.

          [OBJECT TYPE]

          Is the name of a python type from the types module. The name is
          given in lowercase without the ending type, ex. StringType is
          written string. By adding a type here only objects matching the
          given type are matched. Using all here makes the pattern match all
          types (this is the default).

        Options:

          -a: makes the pattern match even objects whose names start with a
          single underscore.  These names are normally omitted from the
          search.

          -i/-c: make the pattern case insensitive/sensitive.  If neither of
          these options are given, the default is read from your configuration
          file, with the option ``InteractiveShell.wildcards_case_sensitive``.
          If this option is not specified in your configuration file, IPython's
          internal default is to do a case sensitive search.

          -e/-s NAMESPACE: exclude/search a given namespace.  The pattern you
          specify can be searched in any of the following namespaces:
          'builtin', 'user', 'user_global','internal', 'alias', where
          'builtin' and 'user' are the search defaults.  Note that you should
          not use quotes when specifying namespaces.

          -l: List all available object types for object matching. This function
          can be used without arguments.

          'Builtin' contains the python module builtin, 'user' contains all
          user data, 'alias' only contain the shell aliases and no python
          objects, 'internal' contains objects used by IPython.  The
          'user_global' namespace is only used by embedded IPython instances,
          and it contains module-level globals.  You can add namespaces to the
          search with -s or exclude them with -e (these options can be given
          more than once).

        Examples
        --------
        ::

          %psearch a*            -> objects beginning with an a
          %psearch -e builtin a* -> objects NOT in the builtin space starting in a
          %psearch a* function   -> all functions beginning with an a
          %psearch re.e*         -> objects beginning with an e in module re
          %psearch r*.e*         -> objects that start with e in modules starting in r
          %psearch r*.* string   -> all strings in modules beginning with r

        Case sensitive search::

          %psearch -c a*         list all object beginning with lower case a

        Show objects beginning with a single _::

          %psearch -a _*         list objects beginning with a single underscore

        List available objects::

          %psearch -l            list all available object types
        )
user_localuser_globalbuiltinzcias:e:lT)list_allFlicsea)show_allignore_case
list_typesN)	parse_optionsgetr   	inspectorr   wildcards_case_sensitiveextendns_tableshowtraceback)r   r   
def_searchoptsargsoptr   r   rC   rB   
ns_excludenm	ns_searchs                r!   r   zNamespaceMagics.psearch|   s    p >
 &&{:t&L	Thh

//)) 
$;J $;KD[K#<<<K 	#c"+& #C+
Z",EB*0DRE	E	"D	 X+*V	 F	"!s   	CC%C	 	Cc                    | j                   j                  }| j                   j                  }t               }|D cg c],  }|j	                  d      s||   |j                  ||      ur|. }}|j                         }|r5t        |      }|D cg c]  }t        ||         j                  |v s|! }}|j                          |S c c}w c c}w )a  Return a sorted list of all interactive variables.

        If arguments are given, only variables of types matching these
        arguments are returned.

        Examples
        --------
        Define two variables and list them with who_ls::

          In [1]: alpha = 123

          In [2]: beta = 'test'

          In [3]: %who_ls
          Out[3]: ['alpha', 'beta']

          In [4]: %who_ls int
          Out[4]: ['alpha']

          In [5]: %who_ls str
          Out[5]: ['beta']
        _)r   user_nsuser_ns_hiddenobject
startswithrE   splitsettype__name__sort)	r   r   rT   rU   nonmatchingr<   r3   typelisttypesets	            r!   who_lszNamespaceMagics.who_ls   s    4 **$$22h" Ma||C(QZ~'9'9!['II  M M $$&(mG!JT'!*%5%>%>'%I1JCJ

M Ks   1CC/Cc                     | j                  |      }|s|rt        d       yt        d       yd}|D ])  }t        |dz   d       |dz  }|d	kD  sd}t                + t                y)
a  Print all interactive variables, with some minimal formatting.

        If any arguments are given, only variables whose type matches one of
        these are printed.  For example::

          %who function str

        will only list functions and strings, excluding all other types of
        variables.  To find the proper type names, simply use type(var) at a
        command line to see how python prints type names.  For example:

        ::

          In [1]: type('hello')\
          Out[1]: <type 'str'>

        indicates that the type name for strings is 'str'.

        ``%who`` always excludes executed names loaded through your configuration
        file and things which are internal to IPython.

        This is deliberate, as typically you may load many modules and the
        purpose of %who is to show you only what you've manually defined.

        Examples
        --------

        Define two variables and list them with who::

          In [1]: alpha = 123

          In [2]: beta = 'test'

          In [3]: %who
          alpha   beta

          In [4]: %who int
          alpha

          In [5]: %who str
          beta
        'No variables match your requested type.Interactive namespace is empty.Nr   	 endr      )r`   r1   )r   r   varlistcountr<   s        r!   whozNamespaceMagics.who  sz    \ ++k*?@  78  	A!D&c"QJEqy	 	r"   c           	         | j                  |      }|s|rt        d       yt        d       yg d}d}dt        j                  v r	 ddlm} |j                  }dd	ifd
}|D cg c]  }| j                  j                  |    }}g }	|D ]h  }
 ||
      }|dk(  rH|	j                  j                  t        |
j                        t        |
j                                     X|	j                  |       j d}d}d}d}d}d}t        t        t        t         |            t!        |            |z   }t        t        t        t         |	            t!        |            |z   }t        |j#                  |      |j#                  |      z   dz   |z   dz   d||z   t!        |      z   dz   z  z          d}d}t%        |||	      D ]]  \  }}}t        |j'                  ||||      d       ||v r!t        dt        t!        |            z          M||k(  rt        |j(                        j+                  dd      j+                  dd      dd }||k(  r'|j,                  }||j.                  z  }|j0                  }dk  rt        |||fz         t        |||fz  d       ||k  rt        d ||z  d!       t        d ||z  d"       	 t        |      }|j+                  dd%      }t!        |      d&k  rt        |       Gt        |dd' d(z   |d)d z          ` y# t        $ r Y w xY wc c}w # t2        $ r |j5                  t6        d#      }Y ~ d$t9        |      z  }Y xY w)*a%  Like %who, but gives some extra information about each variable.

        The same type filtering of %who can be applied here.

        For all variables, the type is printed. Additionally it prints:

          - For {},[],(): their length.

          - For numpy arrays, a summary with shape, number of
            elements, typecode and size in memory.

          - Everything else: a string representation, snipping their middle if
            too long.

        Examples
        --------
        Define two variables and list them with whos::

          In [1]: alpha = 123

          In [2]: beta = 'test'

          In [3]: %whos
          Variable   Type        Data/Info
          --------------------------------
          alpha      int         123
          beta       str         test
        rb   rc   N)dictlisttuplenumpyr   ndarrayzIPython.core.macro.MacroMacroc                 R    t        |       j                  }j                  ||      S )N)rZ   r[   rE   )vtnabbrevss     r!   	type_namez'NamespaceMagics.whos.<locals>.type_name  s#    a!!B;;r"%%r"   instanceVariableTypez	Data/Info   z{0:<{varwidth}}{1:<{typewidth}}z!%s: %s elems, type `%s`, %s bytesre   
-r   i   i   )varwidth	typewidthrf   zn=, xi (z kb)z Mb)backslashreplacez"<object with id %d (str() failed)>z\n2      z<...>i)r`   r1   sysmodulesrp   rr   r[   ImportErrorr   rT   appendrE   str	__class__maxmaplenljustzipformatshapereplacesizeitemsizedtypeUnicodeEncodeErrorencoder
   id)r   r   varnames	seq_typesndarray_typerr   rx   nri   r^   vvttvarlabel	typelabel	datalabelcolsepvformataformatr   r   kbMbvnamevarvtypevshapevsizevbytesvdtypevstrrw   s                                 @r!   whoszNamespaceMagics.whos^  st   @ ;;{+?@  78
 .	 ckk!0)  '//
 .8	& 3;;Q4::%%a(;; 	$B2B:~S->-0->"@ A #	$ 		68s3s8,-s8}=FCH-.I?&H	hnnX&)CC !#&(:3y>(I!(K#LM 	N "8GH=  	<OE#e'..I.V\_`	!d3s3x=(),&SYY//B7??CH2N,& XXE"3<</F YYFF?'VUFF$CCD'VUFF$CCM{6"9676"967Js8D ||D%0t9r>$K$s)g-ST
:;A 	<U   <h * :::&6&8:DJ?"S'IDs*   L" ' L2L7"	L/.L/7M)M)c                 d   | j                  |ddd      \  }}d|v rd}n	 | j                  j                  dd	      }|st	        d
       yd|v r/| j                  j
                  }| j                         D ]  }||=  n-t        |      dk(  r| j                  j                  dd|v        | j                  }| j                  j
                  }|D ]  }|j                         }|dk(  r?t	        dt        |d         z         | j                  j                  j                          X|dk(  rt	        d       | j                  j                  j                  dz   }	t        d|	      D ]"  }
dt        |
      z   }|j                  |d       $ |j!                  t#        ddd             |j$                  }dg|	z  |j&                  dd dg|	z  |j(                  dd dx|_        x|_        x|_        |_        )|dk(  r:	 ddlm} t7        |j9                               D ]  \  }}t;        ||      s||=  h|dk(  rt	        d       |d   dd= t	        dd !       t	        |d"z           t?        j@                          y# t        $ r d}Y Uw xY w# t<        $ r t	        d       Y w xY w)#a]  Resets the namespace by removing all names defined by the user, if
        called without arguments, or by removing some types of objects, such
        as everything currently in IPython's In[] and Out[] containers (see
        the parameters for details).

        Parameters
        ----------
        -f
            force reset without asking for confirmation.
        -s
            'Soft' reset: Only clears your namespace, leaving history intact.
            References to objects may be kept. By default (without this option),
            we do a 'hard' reset, giving you a new session and removing all
            references to objects from the current session.
        --aggressive
            Try to aggressively remove modules from sys.modules ; this
            may allow you to reimport Python modules that have been updated and
            pick up changes, but can have unintended consequences.

        in
            reset input history
        out
            reset output history
        dhist
            reset directory history
        array
            reset only variables that are NumPy arrays

        See Also
        --------
        reset_selective : invoked as ``%reset_selective``

        Examples
        --------
        ::

          In [6]: a = 1

          In [7]: a
          Out[7]: 1

          In [8]: 'a' in get_ipython().user_ns
          Out[8]: True

          In [9]: %reset -f

          In [1]: 'a' in get_ipython().user_ns
          Out[1]: False

          In [2]: %reset -f in
          Flushing input history

          In [3]: %reset -f dhist in
          Flushing directory history
          Flushing input history

        Notes
        -----
        Calling this magic from clients that do not implement standard input,
        such as the ipython notebook interface, will reset the namespace
        without confirmation.
        sf
aggressivern   )modefTz=Once deleted, variables cannot be recovered. Proceed (y/[n])?r   defaultNothing done.Nr>   r   F)new_sessionr   r3   z"Flushing output cache (%d entries)_ohinzFlushing input historyr   _ir   )r   _ii_iiiarrayrq   z-reset array only works if Numpy is available.dhistzFlushing directory history_dhzDon't know how to reset re   rf   z", please run `%reset?` for details)!rD   r   
ask_yes_nor   r1   rT   r`   r   resetlowerdisplayhookflushprompt_countrangereprpopupdaterm   history_managerinput_hist_parsedinput_hist_rawr   r   r   _i00rp   rr   rn   items
isinstancer   gccollect)r   r   rL   rM   ansrT   r<   iptargetpcr   keyhmrr   r   vals                   r!   r   zNamespaceMagics.reset  s   @ ''T<f'U
d$;Cjj++O , 
 /"$;jj((G[[]  AJ Y!^JJLD<PR ZZ**$$ '	EF\\^F:S=PPQ

&&,,.4./ZZ++881<q" *AtAw,CKKD)* tss<='' ,.$)$$Q'(*tby!!!$69999277"K- "&gmmo!6 +#%c'2 '
+ 7"23EN1% 0c:fCCDO'	ER 	

u , ^ # KIJKs)   J ?1J1JJJJ/.J/c                    | j                  |d      \  }}d|v rd}n	 | j                  j                  dd      }|st	        d       y| j                  j
                  }|st	        d       y	 t        j                  |      }| j                         D ]  }|j                  |      s||=  y# t        $ r d}Y w xY w# t        $ r}t        d	      |d}~ww xY w)
a<  Resets the namespace by removing names defined by the user.

        Input/Output history are left around in case you need them.

        %reset_selective [-f] regex

        No action is taken if regex is not included

        Options
          -f : force reset without asking for confirmation.

        See Also
        --------
        reset : invoked as ``%reset``

        Examples
        --------
        We first fully reset the namespace so your output looks identical to
        this example for pedagogical reasons; in practice you do not need a
        full reset::

          In [1]: %reset -f

        Now, with a clean namespace we can make a few variables and use
        ``%reset_selective`` to only delete names that match our regexp::

          In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8

          In [3]: who_ls
          Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']

          In [4]: %reset_selective -f b[2-3]m

          In [5]: who_ls
          Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']

          In [6]: %reset_selective -f d

          In [7]: who_ls
          Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']

          In [8]: %reset_selective -f c

          In [9]: who_ls
          Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']

          In [10]: %reset_selective -f b

          In [11]: who_ls
          Out[11]: ['a']

        Notes
        -----
        Calling this magic from clients that do not implement standard input,
        such as the ipython notebook interface, will reset the namespace
        without confirmation.
        r   Tz>Once deleted, variables cannot be recovered. Proceed (y/[n])? r   r   r   Nz)No regex pattern specified. Nothing done.z*regex must be a string or compiled pattern)rD   r   r   r   r1   rT   r   compile	TypeErrorr`   search)	r   r   rL   regexr   rT   mr?   r<   s	            r!   reset_selectivezNamespaceMagics.reset_selective`  s    x ((S9e$;Cjj++P , 
 /"**$$=>UJJu% [[] $88A;
$ ,   U LMSTTUs)   B. .B? .B<;B<?	CCCc                     | j                  |d      \  }}	 | j                  j                  |d|v        y# t        t        f$ r7}t        t        |      j                  dz   t        |      z          Y d}~yd}~ww xY w)a  Delete a variable, trying to clear it from anywhere that
        IPython's machinery has references to it. By default, this uses
        the identity of the named object in the user namespace to remove
        references held under other names. The object is also removed
        from the output history.

        Options
          -n : Delete the specified name from all namespaces, without
          checking their identity.
        r   z: N)	rD   r   del_var	NameError
ValueErrorr1   rZ   r[   r   )r   r   rL   varnamer?   s        r!   xdelzNamespaceMagics.xdel  so     **;s;g	2JJw6:& 	2$q'""D(#a&011	2s   6 A<-A77A<)r   N)r   )r[   
__module____qualname____doc__r   r   r&   r	   r(   r*   r,   r.   r   r`   rk   r   r   r   r    r"   r!   r   r   !   s;   
 7 7( 3 3 <  < < < ? ? a a. v" v"p %  %N <  <| z<  z<x A AF T$ T$l 2 2r"   r   )r   r   r   r   IPython.corer   IPython.core.errorr   r   IPython.core.magicr   r   r   IPython.testing.skipdoctestr	   IPython.utils.encodingr
   IPython.utils.openpyr   IPython.utils.pathr   r   r   r"   r!   <module>r      sM    
 	 
  C ? ? 4 3 - . e
2f e
2 e
2r"   