U
    9%ek!                     @   s   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ddgZ	dddZ
G dd dejZdd
dZG dd dejZeedddZdS )zU
lazy_loader
===========

Makes it easy to load subpackages and functions on demand.
    Nattachloadattach_stubc                    s   |dkri }dkrt  nt dd | D t B  fdd} fdd}tjdd	rt  B D ]}|| q||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                 S   s    i | ]\}}|D ]
}||qqS  r   ).0modattrsattrr   r   S/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/lazy_loader/__init__.py
<dictcomp>B   s
       zattach.<locals>.<dictcomp>c                    s   | krt  d|  S |  krn d |   }t |}t|| }|  |  krjtj }||j| < |S td d|  d S )N.zNo z attribute )	importlibimport_modulegetattrsysmodules__dict__AttributeError)nameZsubmod_pathZsubmodr	   pkg)attr_to_modulespackage_name
submodulesr   r
   __getattr__H   s    



zattach.<locals>.__getattr__c                      s    S Nr   r   )__all__r   r
   __dir__[   s    zattach.<locals>.__dir__ZEAGER_IMPORT )setitemssortedkeysosenvirongetlist)r   r   Zsubmod_attrsr   r   r	   r   )r   r   r   r   r
   r      s    '
c                       s(   e Zd Z fddZ fddZ  ZS )DelayedImportErrorModulec                    s   || _ t j|| d S r   )%_DelayedImportErrorModule__frame_datasuper__init__)self
frame_dataargskwargs	__class__r   r
   r)   f   s    z!DelayedImportErrorModule.__init__c                    sd   |dkrt  | nJ| j}td|d  d|d  d|d  d|d	  d
d|d   
d S )N)r/   __file__Z__frame_dataNo module named 'speczF'

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

----> r   code_context)r(   r   r'   ModuleNotFoundErrorjoinstrip)r*   xfdr.   r   r
   r   j   s    >z$DelayedImportErrorModule.__getattr__)__name__
__module____qualname__r)   r   __classcell__r   r   r.   r
   r&   e   s   r&   Fc                 C   s   zt j|  W S  tk
r    Y nX d| kr:d}t|t tj| }|dkr|rdt	d|  dn8z2t
 d }| |j|j|j|jd}t|dW S ~X tj|}|t j| < tj|j}|| |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

    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.

    r   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.Nr1   '   )r2   r3   r4   r5   r6   r&   )r   r   KeyErrorwarningswarnRuntimeWarningr   util	find_specr7   inspectstackr3   r4   r5   r6   r&   module_from_spec
LazyLoaderloaderexec_module)fullnameZerror_on_importmsgr2   parentr+   modulerL   r   r   r
   r   w   s6    7

c                   @   s(   e Zd ZdZdd ZejdddZdS )_StubVisitorzAAST visitor to parse a stub file for submodules and submod_attrs.c                 C   s   t  | _i | _d S r   )r   _submodules_submod_attrs)r*   r   r   r
   r)      s    z_StubVisitor.__init__)nodec                 C   s\   |j dkrtd|jr@| j|jg }|dd |jD  n| jdd |jD  d S )NrA   z;Only within-module imports are supported (`from .* import`)c                 s   s   | ]}|j V  qd S r   r   r   aliasr   r   r
   	<genexpr>   s     z0_StubVisitor.visit_ImportFrom.<locals>.<genexpr>c                 s   s   | ]}|j V  qd S r   rV   rW   r   r   r
   rY      s     )	level
ValueErrorrQ   rT   
setdefaultextendnamesrS   update)r*   rU   r   r   r   r
   visit_ImportFrom   s    
z_StubVisitor.visit_ImportFromN)r<   r=   r>   __doc__r)   ast
ImportFromr`   r   r   r   r
   rR      s   rR   )r   r3   c              	   C   s   | dr|ntj|d  d}tj|s>td|t|}t|	 }W 5 Q R X 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 )endswithr"   pathsplitextexistsr[   openrb   parsereadrR   visitr   rS   rT   )r   r3   ZstubfilefZ	stub_nodevisitorr   r   r
   r      s    "

)NN)F)ra   rb   r   importlib.utilrH   r"   r   typesrC   r   r   
ModuleTyper&   r   NodeVisitorrR   strr   r   r   r   r
   <module>   s   

R
_