o
    BZhW                     @  s0  d Z ddlmZ ddlZddlZddlmZ ddlm	Z	 ddl
mZmZmZmZmZmZmZmZmZmZ ddlmZ ddlmZ dd	lmZmZ d
dlmZmZmZm Z  ej!rdej"ej#ej$ej f Z%nejZ%G dd de&Z'G dd de'Z(G dd deZ)G dd de)Z*ej+dddZ,G dd de*Z-dS )z/A base class for objects that are configurable.    )annotationsN)deepcopy)dedent)
Any	ContainerDict	HasTraitsInstance	TraitTypedefaultobserveobserve_compatvalidate)warnings)Bunch)indentwrap_paragraphs   )ConfigDeferredConfigLazyConfigValue_is_section_keyc                   @     e Zd ZdS )ConfigurableErrorN__name__
__module____qualname__ r   r   T/var/www/html/lang_env/lib/python3.10/site-packages/traitlets/config/configurable.pyr   (       r   c                   @  r   )MultipleInstanceErrorNr   r   r   r   r   r!   ,   r    r!   c                      s   e Zd Zeedi ZedddZd7 fd	d
Zed8ddZ	d9ddZ
		d:d;ddZeded<ddZd=ddZed>d?d#d$Ze		d:d@d)d*Zed>dAd+d,ZedBd0d1Zed>dCd3d4ZedDd5d6Z  ZS )EConfigurabler   z*traitlets.config.configurable.ConfigurableT)
allow_nonekwargst.AnyreturnNonec                   s    dd}|durdddu r|jd< || _ dd}t jd
i  t  d fdd	}| | |durA|| _n| | j | 	|  D ]
}t
| ||  qNdS )a  Create a configurable given a config config.

        Parameters
        ----------
        config : Config
            If this is empty, default values are used. If config is a
            :class:`Config` instance, it will be used to configure the
            instance.
        parent : Configurable instance, optional
            The parent Configurable instance of this object.

        Notes
        -----
        Subclasses of Configurable must call the :meth:`__init__` method of
        :class:`Configurable` *before* doing anything else and using
        :func:`super`::

            class MyConfigurable(Configurable):
                def __init__(self, config=None):
                    super(MyConfigurable, self).__init__(config=config)
                    # Then any other code you need to finish initialization.

        This ensures that instances will be configured properly.
        parentNconfigchanger   r&   r'   c                   s   | j v r | j  dS dS )zRecord traits set by both config and kwargs.

            They will need to be overridden again after loading config.
            N)nameadd)r*   Zconfig_override_namesr$   r   r   notice_config_overridea   s   
z5Configurable.__init__.<locals>.notice_config_overrider   r*   r   r&   r'   )popgetr)   r(   super__init__setr   _load_configZ	unobservesetattr)selfr$   r(   r)   r.   r+   	__class__r-   r   r3   9   s"   


zConfigurable.__init__	list[str]c                   s    fddt  jD S )zreturn section names as a listc                   s&   g | ]}t |trt  |r|jqS r   
issubclassr"   r   ).0cclsr   r   
<listcomp>   s    z.Configurable.section_names.<locals>.<listcomp>)reversed__mro__r?   r   r?   r   section_names   s   
zConfigurable.section_namescfgr   c                 C  sX   |g}| j r|| j | t }|D ]}|  D ]}||r(|||  qq|S )a  extract my config from a global Config object

        will construct a Config object of only the config values that apply to me
        based on my mro(), as well as those of my parent(s) if they exist.

        If I am Bar and my parent is Foo, and their parent is Tim,
        this will return merge following config sections, in this order::

            [Bar, Foo.Bar, Tim.Foo.Bar]

        With the last item being the highest priority.
        )r(   append_find_my_configr   rD   Z_has_sectionmerge)r7   rE   Zcfgs	my_configr>   Zsnamer   r   r   rG      s   
zConfigurable._find_my_configNrD   list[str] | Nonetraits)dict[str, TraitType[t.Any, t.Any]] | Nonec                 C  sz  |du r
| j dd}|du r|  }| |}|   | D ]\}}||v rMt|tr8t| |}||}nt|t	rD||| }t
| |t| q t|st|tsddlm} t| trm| jdushJ | jj}	ndd
d}	|||}
d| d| jj d}t|
dkr|d|
d  d7 }nt|
dkr|djdt|
d7 }|	| q W d   dS 1 sw   Y  dS )z load traits from a Config objectNTr)   r   )get_close_matchesmsgr%   r&   r'   c                 S  s   t j| tddS )N	   
stacklevel)r   warnUserWarning)rO   r   r   r   rS      s   z'Configurable._load_config.<locals>.warnzConfig option `z` not recognized by `z`.r   z  Did you mean `z`?z#  Did you mean one of: `{matches}`?, )matches)rO   r%   r&   r'   )rK   rD   rG   Zhold_trait_notificationsitems
isinstancer   getattr	get_valuer   r6   r   r   r   difflibrN   LoggingConfigurablelogwarningr9   r   lenformatjoinsorted)r7   rE   rD   rK   rI   r+   Zconfig_valueinitialrN   rS   rV   rO   r   r   r   r5      s@   








"zConfigurable._load_configr)   r*   r   c                 C  s*   | j dd}|  }| j|j||d dS )zUpdate all the class traits having ``config=True`` in metadata.

        For any class trait with a ``config`` metadata attribute that is
        ``True``, we update the trait with the value of the corresponding
        config entry.
        TrM   )rK   rD   N)rK   rD   r5   new)r7   r*   rK   rD   r   r   r   _config_changed   s   
zConfigurable._config_changedc                 C  s&   t | j| _| | | j| dS )z%Update config and load the new valuesN)r   r)   r5   rH   )r7   r)   r   r   r   update_config   s   
zConfigurable.update_configinstHasTraits | Nonestrc                 C  s   |du st || sJ g }ddd | jD }|| j d| d |t|d d  t| jd	d
 D ]\}}| 	||}|| q9d|S )zGet the help string for this class in ReST format.

        If `inst` is given, its current trait values will be used in place of
        class defaults.
        NrU   c                 s  s    | ]}|j V  qd S N)r   r=   pr   r   r   	<genexpr>  s    z.Configurable.class_get_help.<locals>.<genexpr>(z	) optionsr   -TrM   
)
rX   ra   	__bases__rF   r   r_   rb   class_traitsrW   class_get_trait_help)r@   rg   Z
final_helpZbase_classes_vhelpr   r   r   class_get_help   s   
zConfigurable.class_get_helptraitTraitType[t.Any, t.Any]helptext
str | Nonec           	      C  s  |du st || sJ g }d| j d|j }t |ttfrK|jdd}t |tr-d}nd|jj  }|dkrB| d| d	}n| d
| d	}n
| d|jj d}|	| |du ra|j
}|dkrtdt|d}|	t| d|jjv r|	td|   |dur|	tdt||jpd n-z| }W n ty   d}Y nw |durt|dkr|dd d	 }|	td|  d|S )a  Get the helptext string for a single trait.

        :param inst:
            If given, its current trait values will be used in place of
            the class default.
        :param helptext:
            If not given, uses the `help` attribute of the current trait.
        Nz--.multiplicityrF   z<key-1>=<value-1>z<%s-item-1>=... z=<> rp   L   EnumzChoices: %sz	Current: @   =   zDefault: %s)rX   r   r+   r   r   metadatar1   r9   lowerrF   rv   ra   r   r   inforY   default_value_repr	Exceptionr_   )	r@   rx   rg   rz   linesheaderr}   Zsample_valuedvrr   r   r   rs     s@   

"
z!Configurable.class_get_trait_helpc                 C  s   t | | dS )z4Get the help string for a single trait and print it.N)printrw   )r@   rg   r   r   r   class_print_helpD  s   zConfigurable.class_print_helpclassest.Sequence[type[HasTraits]]type[Configurable]c                 C  sT   | }|j dus	J |  D ]}t|tr'||v r'|jdd|j d|u r'|}q|S )a7  Get the class that defines a trait

        For reducing redundant help output in config files.
        Returns the current class if:
        - the trait is defined on this class, or
        - the class where it is defined would not be in the config file

        Parameters
        ----------
        trait : Trait
            The trait to look for
        classes : list
            The list of other classes to consider for redundancy.
            Will return `cls` even if it is not defined on `cls`
            if the defining class is not in `classes`.
        NTrM   )r+   mror<   r"   Zclass_own_traitsr1   )r@   rx   r   Zdefining_clsr(   r   r   r   _defining_classI  s   zConfigurable._defining_class"t.Sequence[type[HasTraits]] | Nonec              	   C  s|  ddd}d}d dd	 | jD }d
| j d| d}|||g}|  d}|r-|j}|s5t| dd}|rC||| |d t| jdd	 D ]k\}}	|	
 }
|r^| |	|}n| }|| u r|	jro|||	j dt|	jv r|d|	   |d|
  n|	jr|||	jddd  |d|j d|  |d| j d| d|
  |d qMd |S )zGet the config section for this class.

        Parameters
        ----------
        classes : list, optional
            The list of other classes in the config file.
            Used to reduce redundant information.
        sri   r&   c                 S  s    d t| d} d| dd S )z"return a commented, wrapped block.z

N   z## rp   z
#  )ra   r   replace)r   r   r   r   r>   s  s   z,Configurable.class_config_section.<locals>.czO#------------------------------------------------------------------------------rU   c                 s  s     | ]}t |tr|jV  qd S rj   r;   rk   r   r   r   rm   {  s    z4Configurable.class_config_section.<locals>.<genexpr>z# rn   z) configurationdescription__doc__r   TrM   r   z#  Choices: %sz#  Default: %srp   r   r   z#  See also: r|   z# c.z = N)r   ri   r&   ri   )ra   rq   r   rr   r1   default_valuerY   rF   rb   rW   r   r   rv   typer   split)r@   r   r>   breakerZparent_classesr   r   Zdescr+   rx   Zdefault_reprdefining_classr   r   r   class_config_sectionh  s<   



z!Configurable.class_config_sectionc           	   	   C  s  g }| j }t| jdd D ]v\}}|jj }|jsq|d |j }d|v r/|d|  7 }n|d| 7 }|| z| }W n t	yK   d}Y nw |durrt
|dkr^|dd d	 }|d
d}|td|  |d |jpvd}|tt| |d qd|S )zwGenerate rST documentation for this class' config options.

        Excludes traits defined on parent classes.
        TrM   r|   r   z : Nr   r   r   z\nz\\nzDefault: ``%s``r   zNo descriptionrp   )r   rb   rr   rW   r9   r+   Zinfo_rstrF   r   r   r_   r   r   rv   r   ra   )	r@   r   	classnamert   rx   ttypeZtermliner   rv   r   r   r   class_config_rst_doc  s4   



z!Configurable.class_config_rst_doc)r$   r%   r&   r'   )r&   r:   )rE   r   r&   r%   )NN)rE   r   rD   rJ   rK   rL   r&   r'   r/   )r)   r   r&   r'   rj   )rg   rh   r&   ri   )rx   ry   rg   rh   rz   r{   r&   ri   )rg   rh   r&   r'   )rx   ry   r   r   r&   r   )r   r   r&   ri   )r&   ri   )r   r   r   r	   r   r)   r(   r3   classmethodrD   rG   r5   r   r   re   rf   rw   rs   r   r   r   r   __classcell__r   r   r8   r   r"   5   s8    H
5
8;r"   c                   @  sJ   e Zd ZdZedddZeddd
dZeddddZ	dddZ
dS )r\   zA parent class for Configurables that log.

    Subclasses have a log trait, and the default behavior
    is to get the logger from the currently running Application.
    z Logger or LoggerAdapter instanceF)rv   r#   r]   proposalr   r&   
LoggerTypec                 C  sD   t |jtjtjfstj| jj d|j dt	dd t
t|jS )Nz..log should be a Logger or LoggerAdapter, got r|      rQ   )rX   valueloggingLoggerLoggerAdapterr   rS   r9   r   rT   tcastr   )r7   r   r   r   r   _validate_log  s   
z!LoggingConfigurable._validate_logc                 C  s@   t | jtr| jd usJ ttj| jjS ddlm} |	 S )Nr   )r]   )
rX   r(   r\   r   r   r   r   r]   Z	traitletsZ
get_logger)r7   r]   r   r   r   _log_default  s
   z LoggingConfigurable._log_defaultlogging.Handler | Nonec                 C  s@   | j sdS t| j tjr| j n| j j}t|ddsdS |jd S )zReturn the default Handler

        Returns None if none can be found

        Deprecated, this now returns the first log handler which may or may
        not be the default one.
        Nhandlersr   )r]   rX   r   r   loggerrY   r   )r7   r   r   r   r   _get_log_handler  s   
z$LoggingConfigurable._get_log_handlerN)r   r   r&   r   )r&   r   )r&   r   )r   r   r   r   r   r]   r   r   r   r   r   r   r   r   r   r\     s    r\   CTSingletonConfigurable)boundc                   @  sL   e Zd ZdZdZedddZeddd	ZedddZedddZ	dS )r   zA configurable that only allows one instance.

    This class is for classes that should only have one instance of itself
    or *any* subclass. To create and retrieve such a class use the
    :meth:`SingletonConfigurable.instance` method.
    Nr&   4t.Generator[type[SingletonConfigurable], None, None]c                 c  s6    |   D ]}t| |rt|tr|tkr|V  qdS )zfWalk the cls.mro() for parent classes that are also singletons

        For use in instance()
        N)r   r<   r   r@   subclassr   r   r   	_walk_mro  s   zSingletonConfigurable._walk_mror'   c                 C  s0   |   sdS |  D ]}t|j| rd|_q
dS )z5unset _instance for this class and singleton parents.N)initializedr   rX   	_instancer   r   r   r   clear_instance  s   z$SingletonConfigurable.clear_instancer@   type[CT]argsr%   r$   r   c                 O  s\   | j du r| |i |}|  D ]}||_ qt| j | r| j S td| j dt| j j )a  Returns a global instance of this class.

        This method create a new instance if none have previously been created
        and returns a previously created instance is one already exists.

        The arguments and keyword arguments passed to this method are passed
        on to the :meth:`__init__` method of the class upon instantiation.

        Examples
        --------
        Create a singleton class using instance, and retrieve it::

            >>> from traitlets.config.configurable import SingletonConfigurable
            >>> class Foo(SingletonConfigurable): pass
            >>> foo = Foo.instance()
            >>> foo == Foo.instance()
            True

        Create a subclass that is retrieved using the base class instance::

            >>> class Bar(SingletonConfigurable): pass
            >>> class Bam(Bar): pass
            >>> bam = Bam.instance()
            >>> bam == Bar.instance()
            True
        NzAn incompatible sibling of 'z(' is already instantiated as singleton: )r   r   rX   r!   r   r   )r@   r   r$   rg   r   r   r   r   instance)  s   


zSingletonConfigurable.instanceboolc                 C  s   t | do	| jduS )zHas an instance been created?r   N)hasattrr   r?   r   r   r   r   U  s   z!SingletonConfigurable.initialized)r&   r   )r&   r'   )r@   r   r   r%   r$   r%   r&   r   )r&   r   )
r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s    
+).r   
__future__r   r   typingr   copyr   textwrapr   Ztraitlets.traitletsr   r   r   r   r	   r
   r   r   r   r   Ztraitlets.utilsr   Ztraitlets.utils.bunchr   Ztraitlets.utils.textr   r   loaderr   r   r   r   TYPE_CHECKINGUnionr   r   r   r   r   r!   r"   r\   TypeVarr   r   r   r   r   r   <module>   s.    0	   1