
    Mh_                        d Z ddlmZ ddlmZmZmZ ddlmZ dZ	ddl
Z
ddlZddlZddlZddlZddlZddlZddlmZmZ ddlmZ  G d	 d
          Zg dZd Zd Zd Zd Zd Zd efd efd efgZe                    d d fg           d Z G d d          Z g dZ!d dZ"eddfdZ#e G d de                      Z$d Z%dS )!a  IPython extension to reload modules before executing user code.

``autoreload`` reloads modules automatically before entering the execution of
code typed at the IPython prompt.

This makes for example the following workflow possible:

.. sourcecode:: ipython

   In [1]: %load_ext autoreload

   In [2]: %autoreload 2

   In [3]: from foo import some_function

   In [4]: some_function()
   Out[4]: 42

   In [5]: # open foo.py in an editor and change some_function to return 43

   In [6]: some_function()
   Out[6]: 43

The module was reloaded without reloading it explicitly, and the object
imported with ``from foo import ...`` was also updated.

Usage
=====

The following magic commands are provided:

``%autoreload``, ``%autoreload now``

    Reload all modules (except those excluded by ``%aimport``)
    automatically now.

``%autoreload 0``, ``%autoreload off``

    Disable automatic reloading.

``%autoreload 1``, ``%autoreload explicit``

    Reload all modules imported with ``%aimport`` every time before
    executing the Python code typed.

``%autoreload 2``, ``%autoreload all``

    Reload all modules (except those excluded by ``%aimport``) every
    time before executing the Python code typed.

``%autoreload 3``, ``%autoreload complete``

    Same as 2/all, but also adds any new objects in the module. See
    unit test at IPython/extensions/tests/test_autoreload.py::test_autoload_newly_added_objects

  Adding ``--print`` or ``-p`` to the ``%autoreload`` line will print autoreload activity to
  standard out. ``--log`` or ``-l`` will do it to the log at INFO level; both can be used
  simultaneously.

``%aimport``

    List modules which are to be automatically imported or not to be imported.

``%aimport foo``

    Import module 'foo' and mark it to be autoreloaded for ``%autoreload 1``

``%aimport foo, bar``

    Import modules 'foo', 'bar' and mark them to be autoreloaded for ``%autoreload 1``

``%aimport -foo``

    Mark module 'foo' to not be autoreloaded.

Caveats
=======

Reloading Python modules in a reliable way is in general difficult,
and unexpected things may occur. ``%autoreload`` tries to work around
common pitfalls by replacing function code objects and parts of
classes previously in the module with new versions. This makes the
following things to work:

- Functions and classes imported via 'from xxx import foo' are upgraded
  to new versions when 'xxx' is reloaded.

- Methods and properties of classes are upgraded on reload, so that
  calling 'c.foo()' on an object 'c' created before the reload causes
  the new code for 'foo' to be executed.

Some of the known remaining caveats are:

- Replacing code objects does not always succeed: changing a @property
  in a class to an ordinary method or a method to a member variable
  can cause problems (but in old objects only).

- Functions that are removed (eg. via monkey-patching) from a module
  before it is reloaded are not upgraded.

- C extension modules cannot be reloaded, and so cannot be autoreloaded.

- While comparing Enum and Flag, the 'is' Identity Operator is used (even in the case '==' has been used (Similar to the 'None' keyword)).

- Reloading a module, or importing the same module by a different name, creates new Enums. These may look the same, but are not.
    )magic_arguments)Magicsmagics_class
line_magic)DeduperReloaderTN)import_modulereload)source_from_cachec                   H    e Zd ZdZ	 dZ	 dZ	 d
dZd Zd Zd Z	d Z
dd	ZdS )ModuleReloaderFTNc                     i | _         i | _        i | _        i | _        i | _        || _        d | _        t                      | _        | 	                    dd           d| _
        d S )Nc                     d S N msgs    ]/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/IPython/extensions/autoreload.py<lambda>z)ModuleReloader.__init__.<locals>.<lambda>   s    4     TF)	check_all	do_reload)failedmodulesskip_modulesold_objectsmodules_mtimesshell_reportr   deduper_reloadercheckhide_errors)selfr   s     r   __init__zModuleReloader.__init__   ss     
 (' !0 1 1 	

TU
333 !r   c                 N    	 | j         |= n# t          $ r Y nw xY wd| j        |<   dS )z-Skip reloading the named module in the futureTN)r   KeyErrorr   r"   module_names     r   mark_module_skippedz"ModuleReloader.mark_module_skipped   sG    	[)) 	 	 	D	)-+&&&    
c                 N    	 | j         |= n# t          $ r Y nw xY wd| j        |<   dS )z9Reload the named module in the future (if it is imported)TN)r   r%   r   r&   s     r   mark_module_reloadablez%ModuleReloader.mark_module_reloadable   sG    	!+.. 	 	 	D	$([!!!r)   c                     |                      |           t          |           |                    d          d         }t          j        |         }||fS )zImport a module, and mark it reloadable

        Returns
        -------
        top_module : module
            The imported module if it is top-level, or the top-level
        top_name : module
            Name of top_module

        .r   )r+   r   splitsysr   )r"   r'   top_name
top_modules       r   aimport_modulezModuleReloader.aimport_module   sU     	##K000k"""$$S))!,[*
8##r   c                    t          |d          r|j        dS t          |dd           dv rdS |j        }t          j                            |          \  }}|                                dk    r|}n"	 t          |          }n# t          $ r Y dS w xY w	 t          j	        |          j
        }n# t          $ r Y dS w xY w||fS )N__file__)NN__name__)N__mp_main____main__z.py)hasattrr4   getattrospathsplitextlowerr
   
ValueErrorstatst_mtimeOSError)r"   modulefilenamer;   extpy_filenamepymtimes          r   filename_and_mtimez!ModuleReloader.filename_and_mtime   s    vz** 	fo.E:6:t,,0QQQ:?G$$X..	c99;;%"KK"/99 " " "!zz"	gk**3GG 	 	 	::	 G##s$   4B 
BBB0 0
B>=B>c           
         | j         s|sdS |s| j        r,t          t          j                                                  }n&t          | j                                                  }|D ]}t          j                            |d          }|| j        v r-|                     |          \  }}|H	 || j	        |         k    r[	 | j
                            |d          |k    r|n# t          $ r || j	        |<   Y w xY w|| j	        |<   |r|                     d| d           	 | j        r"t          |t          | j        | j                   n6| j                            |          rnt          |t          | j                   || j
        v r| j
        |= /#  | j        sAt+          d                    |t/          j        d                    t          j                   || j
        |<   Y xY w| j                                         dS )z/Check whether some modules need to be reloaded.NzReloading 'z'.z[autoreload of {} failed: {}]
   )file)enabledr   listr/   r   keysgetr   rG   r   r   r%   r   autoload_objsuperreloadr	   r   r   r   maybe_reload_moduler!   printformat	traceback
format_excstderrupdate_sources)r"   r   r   r   modnamemrE   rF   s           r   r    zModuleReloader.check   sg    | 	I 	F 	0 	03;++--..GG4<,,..//G +	7 +	7G..A$+++#'#:#:1#=#= K"d1'::: ; ;??;55@@ A	    /6#G, ,3D(  7676667777( A#Avt/?LLLL.BB1EE A#Avt/?@@@"dk11 K47+ ;BB ')=b)A)A  "%	    07DK,,,)7* 	,,.....s    2C&&C=<C=&A0FAG/r   )FT)r5   
__module____qualname__rK   r   rO   r#   r(   r+   r2   rG   r    r   r   r   r   r      s        G*IDL=! ! ! !2. . .) ) )$ $ $$$ $ $47/ 7/ 7/ 7/ 7/ 7/r   r   )__code____defaults____doc____closure____globals____dict__c           	          t           D ]9}	 t          | |t          ||                     ## t          t          f$ r Y 6w xY wdS )z%Upgrade the code object of a functionN)
func_attrssetattrr9   AttributeError	TypeError)oldnewnames      r   update_functionrj   9  sd      	CwsD112222	* 	 	 	D	 s   +??c                     t          j        |           }|D ]/}t          |          | u rt                              |d|           0dS )zUse garbage collector to find all instances that refer to the old
    class definition and update their __class__ to point to the new class
    definition	__class__N)gcget_referrerstypeobject__setattr__)rg   rh   refsrefs       r   update_instancesrt   B  sW    
 C  D 6 699sK5556 6r   c           	         t          | j                                                  D ]}t          | |          }	 t          ||          }||k    du r,nD# t          $ r, 	 t          | |           n# t          t          f$ r Y nw xY wY bt          $ r Y nw xY wt          ||          r	 t          | |t          ||                     # t          t          f$ r Y w xY wt          |j                                                  D ]b}|t          | j                                                  vr8	 t          | |t          ||                     K# t          t          f$ r Y ^w xY wct          | |           dS )zjReplace stuff in the __dict__ of a class, and upgrade
    method code objects, and add new methods, if anyTN)rL   ra   rM   r9   re   delattrrf   r>   update_genericrd   rt   )rg   rh   keyold_objnew_objs        r   update_classr{   N  s    CL%%''((  #s##	c3''G 7"t++ , 	 	 	S!!!!"I.   H 	 	 	 D	
 '7++ 		Cgc3//0000	* 	 	 	D	 CL%%''((  d3<,,..////S'#s"3"34444"I.    0 S#s_   A
BA0/B0BBBB		BB*C

CC2EE&%E&c                     t          | j        |j                   t          | j        |j                   t          | j        |j                   dS )z+Replace get/set/del functions of a propertyN)rw   fdelfgetfset)rg   rh   s     r   update_propertyr   x  sD    38SX&&&38SX&&&38SX&&&&&r   c                 B    t          | |          ot          ||          S r   )
isinstance)abtyps      r   isinstance2r     s!    a4*Q"4"44r   c                 .    t          | |t                    S r   )r   ro   r   r   s     r   r   r     s    +aD)) r   c                 8    t          | |t          j                  S r   )r   typesFunctionTyper   s     r   r   r     s    +aE$677 r   c                 .    t          | |t                    S r   )r   propertyr   s     r   r   r     s    +aH-- r   c                 8    t          | |t          j                  S r   )r   r   
MethodTyper   s     r   r   r     s    Q5+;<< r   c                 6    t          | j        |j                  S r   )rj   __func__r   s     r   r   r     s    QZ@@ r   c                 V    t           D ] \  }} || |          r || |            dS !dS )NTF)UPDATE_RULES)r   r   
type_checkupdates       r   rw   rw     sL    *  
F:a 	F1aLLL44	 5r   c                       e Zd Zd Zd ZdS )	StrongRefc                     || _         d S r   obj)r"   r   s     r   r#   zStrongRef.__init__  s    r   c                     | j         S r   r   )r"   s    r   __call__zStrongRef.__call__  s	    xr   N)r5   rZ   r[   r#   r   r   r   r   r   r     s2              r   r   )r5   r^   __package__
__loader____spec__r4   
__cached____builtins__Fc                    t          |d          o|j        | j        k    }|r|s|t          v rdS n|sdS | j        |f}	 |                    |g                               t          j        |                     n# t          $ r Y nw xY wdS )NrZ   FT)	r8   rZ   r5   	mod_attrs
setdefaultappendweakrefrs   rf   )rB   dri   r   autoload	in_modulerx   s          r   
append_objr     s    \**Ps~/PI  	TY..5 	5?D
!C	S"$$W[%5%56666   4s   ;A; ;
BBc                    |i }t          | j                                                  D ]m\  }}t          | |||          s| j        |f}	 |                    |g                               t          j        |                     ^# t          $ r Y jw xY w	 | j        
                                }| j        }| j                                         || j        d<   |d         | j        d<   n# t          t          t          f$ r Y nw xY w	  ||           } n #  | j                            |            xY wt          | j                                                  D ]\  }}	| j        |f}||vr&||dk    st          | |||	d          s.|	|j        |<   g }
||         D ]4} |            }||
                    |           t!          ||	           5|
r|
||<   ||= | S )a2  Enhanced version of the builtin reload function.

    superreload remembers objects previously in the module, and

    - upgrades the class dictionary of every old class in the module
    - upgrades the code object of every old function and method
    - clears the module's namespace before reloading

    Nr5   r   EnumT)rL   ra   itemsr   r5   r   r   r   rs   rf   copyclearre   r%   r   user_nsrw   )rB   r	   r   r   ri   r   rx   old_dictold_namerz   new_refsold_refry   s                r   rP   rP     sV     &///1122  	c&+tS99 	%	""3++227;s3C3CDDDD 	 	 	D	?''))?&.
#(0(>%%~x0   x((( fo335566 ! !g%k!! 6>>!&+tWdKK " ")EM$"3' 	- 	-GgiiGOOG$$$7G,,,, 	!'KC  Ms1   ;B		
BBAC. .DDD D5c                       e Zd Z fdZe ej                     ej        deddd           ej        ddd	d
d           ej        ddd	d
d           ej        dd	d
d           ej        dd	d
d          dd                                                                                    Zedd            Z	d Z
d Z xZS )AutoreloadMagicsc                      t                      j        |i | t          | j                  | _        d| j        _        d| j        _        t          t          j	                  | _
        d S )NF)superr#   r   r   	_reloaderr   rO   setr/   r   loaded_modules)r"   r   kwrl   s      r   r#   zAutoreloadMagics.__init__  s\    !"r"""'
33#( &+#!#+..r   modenow?a  blank or 'now' - Reload all modules (except those excluded by %%aimport)
             automatically now.

             '0' or 'off' - Disable automatic reloading.

             '1' or 'explicit' - Reload only modules imported with %%aimport every
             time before executing the Python code typed.

             '2' or 'all' - Reload all modules (except those excluded by %%aimport)
             every time before executing the Python code typed.

             '3' or 'complete' - Same as 2/all, but also adds any new
             objects in the module.
             
             By default, a newer autoreload algorithm that diffs the module's source code
             with the previous version and only reloads changed parts is applied for modes
             2 and below. To use the original algorithm, add the `-` suffix to the mode,
             e.g. '%autoreload 2-', or pass in --full.
             )ro   defaultnargshelpz-pz--print
store_trueFz1Show autoreload activity using `print` statements)actionr   r   z-lz--logz)Show autoreload activity using the loggerz--hide-errorszHide autoreload errorsz--fullz$Don't ever use new diffing algorithm c                    t          j        | j        |          }|j                                        }|j         }|                    d          rd}|dd         }|| j        j        _	        t          t          j        d          }|j        fd}|j
        du r|j        du rd | j        _        nA|j
        du r#|j        du r|| j        _        n"| j        _        n|j        du r| j        _        |j        | j        _        |d	k    s|d
k    r| j                            d           dS |dk    s|dk    rd| j        _	        dS |dk    s|dk    r&d| j        _	        d| j        _        d| j        _        dS |dk    s|dk    r&d| j        _	        d| j        _        d| j        _        dS |dk    s|dk    r&d| j        _	        d| j        _        d| j        _        dS t)          d| d          )a*	  %autoreload => Reload modules automatically

        %autoreload or %autoreload now
        Reload all modules (except those excluded by %aimport) automatically
        now.

        %autoreload 0 or %autoreload off
        Disable automatic reloading.

        %autoreload 1 or %autoreload explicit
        Reload only modules imported with %aimport every time before executing
        the Python code typed.

        %autoreload 2 or %autoreload all
        Reload all modules (except those excluded by %aimport) every time
        before executing the Python code typed.

        %autoreload 3 or %autoreload complete
        Same as 2/all, but also but also adds any new objects in the module. See
        unit test at IPython/extensions/tests/test_autoreload.py::test_autoload_newly_added_objects

        The optional arguments --print and --log control display of autoreload activity. The default
        is to act silently; --print (or -p) will print out the names of modules that are being
        reloaded, and --log (or -l) outputs them to the log at INFO level.

        The optional argument --hide-errors hides any errors that can happen when trying to
        reload code.

        Reloading Python modules in a reliable way is in general
        difficult, and unexpected things may occur. %autoreload tries to
        work around common pitfalls by replacing function code objects and
        parts of classes previously in the module with new versions. This
        makes the following things to work:

        - Functions and classes imported via 'from xxx import foo' are upgraded
          to new versions when 'xxx' is reloaded.

        - Methods and properties of classes are upgraded on reload, so that
          calling 'c.foo()' on an object 'c' created before the reload causes
          the new code for 'foo' to be executed.

        Some of the known remaining caveats are:

        - Replacing code objects does not always succeed: changing a @property
          in a class to an ordinary method or a method to a member variable
          can cause problems (but in old objects only).

        - Functions that are removed (eg. via monkey-patching) from a module
          before it is reloaded are not upgraded.

        - C extension modules cannot be reloaded, and so cannot be
          autoreloaded.

        -FN
autoreloadc                 4     |             |            d S r   r   )r   lps    r   plz'AutoreloadMagics.autoreload.<locals>.pl  s!    AcFFFAcFFFFFr   c                     d S r   r   r   s    r   r   z-AutoreloadMagics.autoreload.<locals>.<lambda>  s     r   Tr   r   0off1explicit2all3completezUnrecognized autoreload mode "z".)r   parse_argstringr   r   r=   fullendswithr   r   rK   rR   logging	getLoggerinfologr   r!   r    r   rO   r>   )	r"   lineargsr   enable_deduperreloadloggerr   r   r   s	          @@r   r   zAutoreloadMagics.autoreload  s2   X .tEEy  #'9}== 	#( 9D2F'/"<00K	 	 	 	 	 	 :48u#4#4%5%5DN""Z4x4)+&&)*&&X%&DN"%)%5"2::N  &&&&&S[[DEMM%*DN"""S[[DJ..%)DN"',DN$*/DN'''S[[DEMM%)DN"'+DN$*/DN'''S[[DJ..%)DN"'+DN$*.DN'''FdFFFGGGr   Nc                    |}|st          | j        j                                                  }t          | j        j                                                  }|t
          j        }| j        j        r|                    d           n+|                    dd	                    |          z             |                    dd	                    |          z             dS d |
                    d          D             D ]}|                    d          r7|d	d                                         }| j                            |           N| j                            |          \  }}| j                            ||i           dS )
a"  %aimport => Import modules for automatic reloading.

        %aimport
        List modules to automatically import and not to import.

        %aimport foo
        Import module 'foo' and mark it to be autoreloaded for %autoreload explicit

        %aimport foo, bar
        Import modules 'foo', 'bar' and mark them to be autoreloaded for %autoreload explicit

        %aimport -foo, bar
        Mark module 'foo' to not be autoreloaded for %autoreload explicit, all, or complete, and 'bar'
        to be autoreloaded for mode explicit.
        Nz&Modules to reload:
all-except-skipped
zModules to reload:
%s
 z
Modules to skip:
%s
c                 6    g | ]}|                                 S r   )strip).0_s     r   
<listcomp>z,AutoreloadMagics.aimport.<locals>.<listcomp>  s     BBB!AGGIIBBBr   ,r      )sortedr   r   rM   r   r/   stdoutr   writejoinr.   
startswithr   r(   r2   r   push)	r"   parameter_sstreamrX   	to_reloadto_skip_moduler1   r0   s	            r   aimportzAutoreloadMagics.aimport  s~   "  	<t~5::<<==IT^8==??@@G~~' OGHHHH7#((9:M:MMNNNLL3chhw6G6GGHHHHHBBw}}S/A/ABBB < <%%c** <%abbk//11GN66w????+/>+H+H+Q+Q(J JOOXz$:;;;;< <r   c                 f    | j         j        r$	 | j                                          d S #  Y d S xY wd S r   )r   rK   r    )r"   r   s     r   pre_run_cellzAutoreloadMagics.pre_run_cell  sH    >! 	$$&&&&&		 	s   ) .c                    t          t          j                  | j        z
  }|D ]@}| j                            t          j        |                   \  }}||| j        j        |<   A| j                            |           dS )zFCache the modification times of any modules imported in this executionN)r   r/   r   r   r   rG   r   r   )r"   newly_loaded_modulesrX   r   rF   s        r   post_execute_hookz"AutoreloadMagics.post_execute_hook  s    "3;//$2EE+ 	A 	AG::3;w;OPPJAw"9@-g6""#788888r   )r   )r   N)r5   rZ   r[   r#   r   r   argumentstrr   r   r   r   __classcell__)rl   s   @r   r   r     s       / / / / / $_$&&_  2 _@   _8   _%	   _3	  gH gH gH    3  '& ZjgHR $< $< $< Z$<L  9 9 9 9 9 9 9r   r   c                     t          |           }|                     |           | j                            d|j                   | j                            d|j                   dS )zLoad the extension in IPython.r   post_executeN)r   register_magicseventsregisterr   r   )ipauto_reloads     r   load_ipython_extensionr    s_    "2&&K{###I~{'?@@@I~{'DEEEEEr   )F)&r^   IPython.corer   IPython.core.magicr   r   r   .IPython.extensions.deduperreload.deduperreloadr   __skip_doctest__r:   r/   rT   r   r   rm   r   	importlibr   r	   importlib.utilr
   r   rc   rj   rt   r{   r   r   r   extendrw   r   r   r   rP   r   r  r   r   r   <module>r     s  i iV ) ( ( ( ( ( ? ? ? ? ? ? ? ? ? ? J J J J J J $ 
			 



       				  + + + + + + + + , , , , , ,V/ V/ V/ V/ V/ V/ V/ V/|  
  	6 	6 	6' ' 'T' ' '5 5 5
 *)<877I--?
    =<@@	
           	 	 		   $  &4t C C C CV \9 \9 \9 \9 \9v \9 \9 \9~F F F F Fr   