
    0-Ph*                         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ZdZ	g dZ
 ej                    ZddZ G d dej                  Zddd	d
ZdedefdZ G d dej                  ZdedefdZdS )zU
lazy_loader
===========

Makes it easy to load subpackages and functions on demand.
    Nz0.4)attachloadattach_stubc                     |i }t                      nt                    d |                                D             t                                          z             fd}fd}t          j                            dd          r2t                                                    z  D ]} ||           ||t                    fS )a8  Attach lazily loaded submodules, functions, or other attributes.

    Typically, modules import submodules and attributes as follows::

      import mysubmodule
      import anothersubmodule

      from .foo import someattr

    The idea is to replace a package's `__getattr__`, `__dir__`, and
    `__all__`, such that all imports work exactly the way they would
    with normal imports, except that the import occurs upon first use.

    The typical way to call this function, replacing the above imports, is::

      __getattr__, __dir__, __all__ = lazy.attach(
        __name__,
        ['mysubmodule', 'anothersubmodule'],
        {'foo': ['someattr']}
      )

    This functionality requires Python 3.7 or higher.

    Parameters
    ----------
    package_name : str
        Typically use ``__name__``.
    submodules : set
        List of submodules to attach.
    submod_attrs : dict
        Dictionary of submodule -> list of attributes / functions.
        These attributes are imported as they are used.

    Returns
    -------
    __getattr__, __dir__, __all__

    Nc                 $    i | ]\  }}|D ]}||S  r   ).0modattrsattrs       T/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/lazy_loader/__init__.py
<dictcomp>zattach.<locals>.<dictcomp>G   s?        c5U =Ac       c                 &   | v rt          j         d|            S | v r[ d|           }t          j        |          }t          ||           }| |          k    rt          j                 }||j        | <   |S t          d d|            )N.zNo z attribute )	importlibimport_modulegetattrsysmodules__dict__AttributeError)namesubmod_pathsubmodr   pkgattr_to_modulespackage_name
submoduless        r   __getattr__zattach.<locals>.__getattr__M   s    :*l+C+CT+C+CDDD_$$)CCOD,ACCK,[99F64((D
 t,,,k,/%)T"K !F|!F!F!F!FGGGr   c                       S Nr   )__all__s   r   __dir__zattach.<locals>.__dir__`   s    r   EAGER_IMPORT )setitemssortedkeysosenvirongetlist)r   r   submod_attrsr    r$   r   r#   r   s   ``    @@r   r   r      s%   N UU

__
 $0$6$6$8$8  O Z/"6"6"8"8899GH H H H H H H&     
z~~nb)) ,,..//*< 	 	DKg..r   c                   (     e Zd Z fdZ fdZ xZS )DelayedImportErrorModulec                V    || _         || _         t                      j        |i | d S r"   )%_DelayedImportErrorModule__frame_data"_DelayedImportErrorModule__messagesuper__init__)self
frame_datamessageargskwargs	__class__s        r   r6   z!DelayedImportErrorModule.__init__k   s4    & $)&)))))r   c                 "   |dv r#t                                          |           d S | j        }t          | j         d|d          d|d          d|d          dd	                    |d
         pd	                                           	          )N)r<   __file____frame_data	__messagezE

This error is lazily reported, having originally occured in
  File filenamez, line linenoz, in functionz

----> r&   code_context)r5   r    r3   ModuleNotFoundErrorr4   joinstrip)r7   xfdr<   s      r   r    z$DelayedImportErrorModule.__getattr__p   s    FFFGG""""""B%> E EZ.E E13HE EDFzNE E N!3!9r::@@BBE E  r   )__name__
__module____qualname__r6   r    __classcell__)r<   s   @r   r1   r1   j   sQ        * * * * *

 
 
 
 
 
 
 
 
r   r1   F)requireerror_on_importc                   t           5  t          j                            |           }|du}|r||cddd           S d| v rd}t	          j        |t                     d}|s#t          j        	                    |           }|du}|sd|  d}n?|=	 t          |          }n&# t          $ r}t          d|  d          |d}~ww xY wd| d}|sp|rt          |          d	dl}		 |	                                d
         }
|
j        |
j        |
j        |
j        d}t'          |d|          ~
cddd           S # ~
w xY w|gt          j                            |          }|t          j        | <   t          j                            |j                  }|                    |           ddd           n# 1 swxY w Y   |S )a  Return a lazily imported proxy for a module.

    We often see the following pattern::

      def myfunc():
          import numpy as np
          np.norm(...)
          ....

    Putting the import inside the function prevents, in this case,
    `numpy`, from being imported at function definition time.
    That saves time if `myfunc` ends up not being called.

    This `load` function returns a proxy module that, upon access, imports
    the actual module.  So the idiom equivalent to the above example is::

      np = lazy.load("numpy")

      def myfunc():
          np.norm(...)
          ....

    The initial import time is fast because the actual import is delayed
    until the first attribute is requested. The overall import time may
    decrease as well for users that don't make use of large portions
    of your library.

    Warning
    -------
    While lazily loading *sub*packages technically works, it causes the
    package (that contains the subpackage) to be eagerly loaded even
    if the package is already lazily loaded.
    So, you probably shouldn't use subpackages with this `load` feature.
    Instead you should encourage the package maintainers to use the
    `lazy_loader.attach` to make their subpackages load lazily.

    Parameters
    ----------
    fullname : str
        The full name of the module or submodule to import.  For example::

          sp = lazy.load('scipy')  # import scipy as sp

    require : str
        A dependency requirement as defined in PEP-508.  For example::

          "numpy >=1.24"

        If defined, the proxy module will raise an error if the installed
        version does not satisfy the requirement.

    error_on_import : bool
        Whether to postpone raising import errors until the module is accessed.
        If set to `True`, import errors are raised as soon as `load` is called.

    Returns
    -------
    pm : importlib.util._LazyModule
        Proxy module.  Can be used like any regularly imported module.
        Actual loading of the module occurs upon first attribute request.

    Nr   zsubpackages can technically be lazily loaded, but it causes the package to be eagerly loaded even if it is already lazily loaded.So, you probably shouldn't use subpackages with this lazy feature.zNo module named ''zFound module 'zf' but cannot test requirement '{require}'. Requirements must match distribution name, not module name.z'No distribution can be found matching 'r      )rA   rB   rC   rD   r1   )r9   )
threadlockr   r   r-   warningswarnRuntimeWarningr   util	find_spec_check_requirementrE   
ValueErrorinspectstackrA   rB   rC   rD   r1   module_from_spec
LazyLoaderloaderexec_module)fullnamerN   rO   modulehave_modulemsgspecnot_found_messageer[   parentr8   r_   s                r   r   r   }   s   ~ 
 >' >'**D(  	7?>' >' >' >' >' >' >' >' (??U 
 M#~... 	+>++H55Dd*K 	U ?H ? ? ? 099&    RX R R R  	 !U' T T T 	 =)*;<<<NNN + &$m &$*$7	 
 0.-   o>' >' >' >' >' >' >' >'n 



^44T::F$*CK!^..t{;;Fv&&&}>' >' >' >' >' >' >' >' >' >' >' >' >' >' >'@ MsU   )F4AF4B! F4!
C+B??C F4%AD9+F49D<<A,F44F8;F8rN   returnc                     ddl }	 ddlm} n# t          $ r ddl}Y nw xY w|j                            |           }|j                            |	                    |j
                  d          S )a  Verify that a package requirement is satisfied

    If the package is required, a ``ModuleNotFoundError`` is raised
    by ``importlib.metadata``.

    Parameters
    ----------
    require : str
        A dependency requirement as defined in PEP-508

    Returns
    -------
    satisfied : bool
        True if the installed version of the dependency matches
        the specified version, False otherwise.
    r   NT)prereleases)packaging.requirementsimportlib.metadatametadataImportErrorimportlib_metadatarequirementsRequirement	specifiercontainsversionr   )rN   	packagingrp   reqs       r   rY   rY      s    " "!!!"7777777 " " "!!!!!!" 
 
,
,W
5
5C=!!""38,, "   s    c                   .    e Zd ZdZd Zdej        fdZdS )_StubVisitorzAAST visitor to parse a stub file for submodules and submod_attrs.c                 :    t                      | _        i | _        d S r"   )r'   _submodules_submod_attrs)r7   s    r   r6   z_StubVisitor.__init__!  s    55r   nodec                 b   |j         dk    rt          d          |j        rd| j                            |j        g           }d |j        D             }d|v rt          d|j         d          |                    |           d S | j                            d |j        D                        d S )NrR   z;Only within-module imports are supported (`from .* import`)c                     g | ]	}|j         
S r   r   r	   aliass     r   
<listcomp>z1_StubVisitor.visit_ImportFrom.<locals>.<listcomp>,  s    :::euz:::r   *z4lazy stub loader does not support star import `from z
 import *`c              3   $   K   | ]}|j         V  d S r"   r   r   s     r   	<genexpr>z0_StubVisitor.visit_ImportFrom.<locals>.<genexpr>4  s$      #G#G5EJ#G#G#G#G#G#Gr   )	levelrZ   rb   r|   
setdefaultnamesextendr{   update)r7   r}   r   aliasess       r   visit_ImportFromz_StubVisitor.visit_ImportFrom%  s    :??M   ; 
	H,77RHHE::tz:::Gg~~ 5![5 5 5   LL!!!!!###G#GDJ#G#G#GGGGGGr   N)rJ   rK   rL   __doc__r6   ast
ImportFromr   r   r   r   ry   ry     sM        KK     HS^ H H H H H Hr   ry   r   rA   c                    |                     d          r|n't          j                            |          d          d}t          j                            |          st          d|          t          |          5 }t          j        |	                                          }ddd           n# 1 swxY w Y   t                      }|                    |           t          | |j        |j                  S )a#  Attach lazily loaded submodules, functions from a type stub.

    This is a variant on ``attach`` that will parse a `.pyi` stub file to
    infer ``submodules`` and ``submod_attrs``. This allows static type checkers
    to find imports, while still providing lazy loading at runtime.

    Parameters
    ----------
    package_name : str
        Typically use ``__name__``.
    filename : str
        Path to `.py` file which has an adjacent `.pyi` file.
        Typically use ``__file__``.

    Returns
    -------
    __getattr__, __dir__, __all__
        The same output as ``attach``.

    Raises
    ------
    ValueError
        If a stub file is not found for `filename`, or if the stubfile is formmated
        incorrectly (e.g. if it contains an relative import from outside of the module)
    ir   z.pyiz+Cannot load imports from non-existent stub N)endswithr+   pathsplitextexistsrZ   openr   parsereadry   visitr   r{   r|   )r   rA   stubfilef	stub_nodevisitors         r   r   r   7  s   6 %%c**V273C3CH3M3Ma3P0V0V0V  7>>(## USxSSTTT	h (1Iaffhh''	( ( ( ( ( ( ( ( ( ( ( ( ( ( ( nnGMM), 3W5JKKKs    'B33B7:B7)NN)r   r   r   importlib.utilr+   r   	threadingtypesrT   __version__r#   LockrS   r   
ModuleTyper1   r   strboolrY   NodeVisitorry   r   r   r   r   <module>r      sy    


         				 



      
+
+
+ Y^
O/ O/ O/ O/d    u/   & #E     D     >H H H H H3? H H H2&Lc &LS &L &L &L &L &L &Lr   