o
    ˷eK                     @   s8  d 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m	Z	m
Z
 ddlmZ G dd dZg dZd	d
 Zdd Zdd Zdd Zdd Zdd efdd efdd efgZedd dd fg dd ZG dd dZg dZd(dd Ze
ddfd!d"Zdd#lmZmZmZ eG d$d% d%eZd&d' Z dS ))aY
  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``

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

``%autoreload 0``

    Disable automatic reloading.

``%autoreload 1``

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

``%autoreload 2``

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

``%autoreload 3``

    Reload all modules AND autoload newly added objects
    every time before executing the Python code typed.

``%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.
T    N)import_modulereload)source_from_cachec                   @   sR   e Zd ZdZ	 dZ	 dZ	 dddZdd Zdd	 Zd
d Z	dd Z
dddZdS )ModuleReloaderFTNc                 C   s6   i | _ i | _i | _i | _i | _|| _| jddd d S )NTF)	check_all	do_reload)failedmodulesskip_modulesold_objectsmodules_mtimesshellcheck)selfr    r   T/var/www/ideatree/venv/lib/python3.10/site-packages/IPython/extensions/autoreload.py__init__   s   zModuleReloader.__init__c                 C   .   z| j |= W n	 ty   Y nw d| j|< dS )z-Skip reloading the named module in the futureTN)r	   KeyErrorr
   r   module_namer   r   r   mark_module_skipped      z"ModuleReloader.mark_module_skippedc                 C   r   )z9Reload the named module in the future (if it is imported)TN)r
   r   r	   r   r   r   r   mark_module_reloadable   r   z%ModuleReloader.mark_module_reloadablec                 C   s2   |  | 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_moduler   r   r   aimport_module   s
   

zModuleReloader.aimport_modulec                 C   s   t |dr
|jd u rdS t|dd dv rdS |j}tj|\}}| dkr*|}nzt|}W n
 ty:   Y dS w zt	|j
}W ||fS  tyP   Y dS w )N__file__)NN__name__)N__mp_main____main__z.py)hasattrr    getattrospathsplitextlowerr   
ValueErrorstatst_mtimeOSError)r   modulefilenamer'   extpy_filenamepymtimer   r   r   filename_and_mtime   s&   z!ModuleReloader.filename_and_mtimec                 C   s<  | j s|sdS |s| jrttj }nt| j }|D ]~}tj|d}|| jv r,q| |\}}|du r8qz|| j	| krBW qW n t
yQ   || j	|< Y qw | j|d|kr\q|| j	|< |rz| jrqt|t| j| j nt|t| j || jv r| j|= W q   td|tdtjd || j|< Y qqdS )z/Check whether some modules need to be reloaded.Nz[autoreload of {} failed: {}]
   )file)enabledr   listr   r	   keysgetr
   r3   r   r   r   autoload_objsuperreloadr   r   r   printformat	traceback
format_excstderr)r   r   r   r	   modnamemr1   r2   r   r   r   r      sR   






zModuleReloader.checkN)FT)r!   
__module____qualname__r6   r   r:   r   r   r   r   r3   r   r   r   r   r   r      s    
r   )__code____defaults____doc____closure____globals____dict__c              
   C   s:   t D ]}zt| |t|| W q ttfy   Y qw dS )z%Upgrade the code object of a functionN)
func_attrssetattrr%   AttributeError	TypeError)oldnewnamer   r   r   update_function  s   rS   c                 C   s*   t | }|D ]}t|| u r||_qd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
    definitionN)gcget_referrerstype	__class__)rP   rQ   refsrefr   r   r   update_instances&  s   
rZ   c                 C   s   t | j D ]W}t| |}zt||}||kdu rW qW n$ ty9   zt| | W n ttfy6   Y nw Y q tyA   Y nw t||rHqzt	| |t|| W q ttfy^   Y qw t |j D ]"}|t | j vrzt	| |t|| W qf ttfy   Y qfw qft
| | dS )zjReplace stuff in the __dict__ of a class, and upgrade
    method code objects, and add new methods, if anyTN)r7   rK   r8   r%   rN   delattrrO   r*   update_genericrM   rZ   )rP   rQ   keyold_objnew_objr   r   r   update_class2  sB   


r`   c                 C   s.   t | j|j t | j|j t | j|j dS )z+Replace get/set/del functions of a propertyN)r\   fdelfgetfset)rP   rQ   r   r   r   update_property\  s   rd   c                 C   s   t | |o	t ||S rC   )
isinstance)abtypr   r   r   isinstance2c  s   ri   c                 C      t | |tS rC   )ri   rV   rf   rg   r   r   r   <lambda>h      rl   c                 C      t | |tjS rC   )ri   typesFunctionTyperk   r   r   r   rl   i      c                 C   rj   rC   )ri   propertyrk   r   r   r   rl   j  rm   c                 C   rn   rC   )ri   ro   
MethodTyperk   r   r   r   rl   o  rq   c                 C   s   t | j|jS rC   )rS   __func__rk   r   r   r   rl   p  rq   c                 C   s,   t D ]\}}|| |r|| |  dS qdS )NTF)UPDATE_RULES)rf   rg   
type_checkupdater   r   r   r\   v  s   

r\   c                   @   s   e Zd Zdd Zdd ZdS )	StrongRefc                 C   s
   || _ d S rC   obj)r   rz   r   r   r   r     s   
zStrongRef.__init__c                 C   s   | j S rC   ry   r   r   r   r   __call__  s   zStrongRef.__call__N)r!   rD   rE   r   r|   r   r   r   r   rx   ~  s    rx   )r!   rH   __package__
__loader____spec__r    
__cached____builtins__Fc                 C   sr   t |do
|j| jk}|r|s|tv rdS n|sdS | j|f}z||g t| W dS  ty8   Y dS w )NrD   FT)	r$   rD   r!   	mod_attrs
setdefaultappendweakrefrY   rO   )r.   drR   rz   autoload	in_moduler]   r   r   r   
append_obj  s   
r   c              
   C   s  |du ri }t | j D ](\}}t| |||sq| j|f}z||g t| W q t	y5   Y qw z| j
 }| j}| j  || jd< |d | jd< W n t	ttfy]   Y nw z|| } W n
   | j|  t | j D ]H\}}	| j|f}||vr|du s|dkst| |||	dsqv|	|j|< g }
|| D ]}| }|du rq|
| t||	 q|
r|
||< qv||= qv| 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

    Nr!   r~   EnumT)r7   rK   itemsr   r!   r   r   r   rY   rO   copyclearrN   r   rw   user_nsr\   )r.   r   r   r   rR   rz   r]   old_dictold_namer_   new_refsold_refr^   r   r   r   r;     sZ   








r;   )Magicsmagics_class
line_magicc                       sH   e Zd Z fddZedddZedddZd	d
 Zdd Z  Z	S )AutoreloadMagicsc                    s>   t  j|i | t| j| _d| j_d| j_ttj	| _
d S )NF)superr   r   r   	_reloaderr   r:   setr   r	   loaded_modules)r   rf   kwrW   r   r   r     s
   zAutoreloadMagics.__init__ c                 C   s   |dkr| j d dS |dkrd| j _dS |dkr$d| j _d| j _dS |dkr6d| j _d| j _d| j _dS |dkrHd| j _d| j _d| j _dS dS )	ar  %autoreload => Reload modules automatically

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

        %autoreload 0
        Disable automatic reloading.

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

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

        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.

        r   T0F123N)r   r   r6   r   r:   )r   parameter_sr   r   r   
autoreload  s    -zAutoreloadMagics.autoreloadNc           	      C   s   |}|s;t | jj }t | jj }|du rtj}| jjr%|d n
|dd	|  |dd	|  dS |
drN|dd }| j| dS dd	 |d
D D ]}| j|\}}| j||i qXd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 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 for %autoreload 1
        Nz&Modules to reload:
all-except-skipped
zModules to reload:
%s
 z
Modules to skip:
%s
-   c                 S   s   g | ]}|  qS r   )strip).0_r   r   r   
<listcomp>V  s    z,AutoreloadMagics.aimport.<locals>.<listcomp>,)sortedr   r	   r8   r
   r   stdoutr   writejoin
startswithr   r   r   r   push)	r   r   streamrA   	to_reloadto_skip_moduler   r   r   r   r   aimport7  s"   
zAutoreloadMagics.aimportc                 C   s*   | j jrz| j   W d S    Y d S d S rC   )r   r6   r   r{   r   r   r   pre_run_cell\  s   zAutoreloadMagics.pre_run_cellc                 C   sT   t tj| j }|D ]}| jtj| \}}|dur!|| jj|< q
| j| dS )zFCache the modification times of any modules imported in this executionN)r   r   r	   r   r   r3   r   rw   )r   newly_loaded_modulesrA   r   r2   r   r   r   post_execute_hookc  s   z"AutoreloadMagics.post_execute_hook)r   )r   N)
r!   rD   rE   r   r   r   r   r   r   __classcell__r   r   r   r   r     s    <$r   c                 C   s6   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_reloadr   r   r   load_ipython_extensionn  s   
r   )F)!rH   __skip_doctest__r&   r   r>   ro   r   rT   	importlibr   r   importlib.utilr   r   rL   rS   rZ   r`   rd   ri   ru   extendr\   rx   r   r   r;   IPython.core.magicr   r   r   r   r   r   r   r   r   <module>   sJ    c 
	*




J|