a
    õ£Be§W  ã                   @  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!rÈe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                   @  s   e Zd ZdS )ÚConfigurableErrorN©Ú__name__Ú
__module__Ú__qualname__© r   r   ú`/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/traitlets/config/configurable.pyr   (   s   r   c                   @  s   e Zd ZdS )ÚMultipleInstanceErrorNr   r   r   r   r   r   ,   s   r   c                      s$  e Zd Zeedi ƒZeddd�Zdddœ‡ fdd	„Zed
dœdd„ƒZ	dddœdd„Z
d7dddddœdd„Zedƒedddœdd„ƒƒZdddœdd„Zed8d d!d"œd#d$„ƒZed9d%d d&d!d'œd(d)„ƒZed:d dd"œd*d+„ƒZed%d,d-d.œd/d0„ƒZed;d1d!d2œd3d4„ƒZed!dœd5d6„ƒZ‡  ZS )<ÚConfigurabler   z*traitlets.config.configurable.ConfigurableT)Ú
allow_noneút.AnyÚNone)ÚkwargsÚreturnc                   s¼   ˆ  dd¡}|dur4ˆ dd¡du r.|jˆd< || _ˆ  dd¡}tƒ jf i ˆ¤Ž tƒ ‰ dddœ‡ ‡fdd„}|  |¡ |durˆ|| _n|  | j¡ |  	|¡ ˆ D ]}t
| |ˆ| ƒ q¢d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Úconfigr   r#   ©Úchanger%   c                   s   | j ˆv rˆ  | j ¡ dS )z‚Record 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_override)ÚpopÚgetr'   r&   ÚsuperÚ__init__Úsetr   Ú_load_configZ	unobserveÚsetattr)Úselfr$   r&   r'   r-   r*   ©Ú	__class__r,   r   r1   9   s     


zConfigurable.__init__z	list[str]©r%   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_namesr   )Úcfgr%   c                 C  sX   |g}| j r| | j  |¡¡ tƒ }|D ]*}|  ¡ D ]}| |¡r4| || ¡ q4q(|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   rB   Z_has_sectionÚmerge)r5   rC   ZcfgsÚ	my_configr<   Zsnamer   r   r   rE   Š   s    
zConfigurable._find_my_configNzlist[str] | Nonez)dict[str, TraitType[t.Any, t.Any]] | None)rC   rB   Útraitsr%   c                 C  sˆ  |du r| j dd�}|du r$|  ¡ }|  |¡}|  ¡ ��: | ¡ D �]\}}||v ržt|tƒrtt| |ƒ}| |¡}nt|t	ƒrŒ| || ¡}t
| |t|ƒƒ qBt|ƒsBt|tƒsBddlm} t| tƒrÞ| jdusÔJ ‚| jj}	ndddœd	d
„}	|||ƒ}
d|› d| jj› d�}t|
ƒdk�r2|d|
d › d�7 }n(t|
ƒdk�rZ|djd t|
ƒ¡d�7 }|	|ƒ qBW d  ƒ n1 �sz0    Y  dS )z load traits from a Config objectNT©r'   r   )Úget_close_matchesr"   r#   )Úmsgr%   c                 S  s   t j| tdd�S )Né	   ©Ú
stacklevel)r   ÚwarnÚUserWarning)rK   r   r   r   rO   Ê   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)rH   rB   rE   Zhold_trait_notificationsÚitemsÚ
isinstancer   ÚgetattrÚ	get_valuer   r4   r   r   r   ÚdifflibrJ   ÚLoggingConfigurableÚlogÚwarningr7   r   ÚlenÚformatÚjoinÚsorted)r5   rC   rB   rH   rG   r*   Zconfig_valueÚinitialrJ   rO   rR   rK   r   r   r   r3   £   s:    






ÿzConfigurable._load_configr'   r   r(   c                 C  s*   | j dd�}|  ¡ }| j|j||d� dS )zòUpdate 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.
        TrI   )rH   rB   N)rH   rB   r3   Únew)r5   r)   rH   rB   r   r   r   Ú_config_changedØ   s    
zConfigurable._config_changed)r'   r%   c                 C  s&   t | jƒ| _|  |¡ | j |¡ dS )z%Update config and load the new valuesN)r   r'   r3   rF   )r5   r'   r   r   r   Úupdate_configê   s    
zConfigurable.update_configzHasTraits | NoneÚstr)Úinstr%   c                 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 ]\}}|  	||¡}| |¡ qrd |¡S )z¢Get 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.
        NrQ   c                 s  s   | ]}|j V  qd S ©N)r   ©r;   Úpr   r   r   Ú	<genexpr>  ó    z.Configurable.class_get_help.<locals>.<genexpr>ú(z	) optionsr   ú-TrI   Ú
)
rT   r]   Ú	__bases__rD   r   r[   r^   Úclass_traitsrS   Úclass_get_trait_help)r>   rd   Z
final_helpZbase_classesÚ_ÚvÚhelpr   r   r   Úclass_get_helpú   s    zConfigurable.class_get_helpzTraitType[t.Any, t.Any]z
str | None)Útraitrd   Úhelptextr%   c           	      C  s¤  |du st || ƒsJ ‚g }d| j› d|j› �}t |ttfƒr–|j dd¡}t |tƒrZd}nd|jj ¡  }|dkr„|› d|› d	�}qª|› d
|› d	�}n|› d|jj› d�}| 	|¡ |du rÂ|j
}|dkrèd t|dƒ¡}| 	t|ƒ¡ d|jjv �r| 	td| ¡  ƒ¡ |du�r:| 	tdt||j�p,dƒ›�ƒ¡ n`z| ¡ }W n t�y^   d}Y n0 |du�ršt|ƒ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--Ú.ÚmultiplicityrD   z<key-1>=<value-1>z<%s-item-1>ú=ú...ú z=<ú>Ú rl   éL   ÚEnumzChoices: %sz	Current: é@   é=   zDefault: %s)rT   r   r*   r   r   Úmetadatar/   r7   ÚlowerrD   rr   r]   r   r   ÚinforU   Údefault_value_reprÚ	Exceptionr[   )	r>   rt   rd   ru   ÚlinesÚheaderrw   Zsample_valueÚdvrr   r   r   ro     s>    


$

z!Configurable.class_get_trait_helpc                 C  s   t |  |¡ƒ dS )z4Get the help string for a single trait and print it.N)Úprintrs   )r>   rd   r   r   r   Úclass_print_helpD  s    zConfigurable.class_print_helpzt.Sequence[type[HasTraits]]ztype[Configurable])rt   Úclassesr%   c                 C  sT   | }|j dusJ ‚|  ¡ D ]4}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`.
        NTrI   )r*   Úmror:   r    Zclass_own_traitsr/   )r>   rt   r‹   Zdefining_clsr&   r   r   r   Ú_defining_classI  s    ÿþýzConfigurable._defining_classz"t.Sequence[type[HasTraits]] | None)r‹   r%   c              	   C  sˆ  dddœdd„}d}d  dd„ | jD ƒ¡}d	| j› d
|› d�}|||g}|  ¡  d¡}|r`|j}|spt| ddƒ}|rŒ| ||ƒ¡ | d¡ t| jdd� 	¡ ƒD ]Ü\}}	|	 
¡ }
|rÂ|  |	|¡}n| }|| u �r|	jræ| ||	jƒ¡ dt|	ƒjv �r| d|	 ¡  ¡ | d|
 ¡ n<|	j�r<| ||	j dd¡d ƒ¡ | d|j› d|› �¡ | d| j› d|› d|
› �¡ | d¡ q d  |¡S )zãGet the config section for this class.

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

éN   z## rl   z
#  )r]   r   Úreplace)rŽ   r   r   r   r<   s  s    z,Configurable.class_config_section.<locals>.czO#------------------------------------------------------------------------------rQ   c                 s  s   | ]}t |tƒr|jV  qd S re   r9   rf   r   r   r   rh   {  ri   z4Configurable.class_config_section.<locals>.<genexpr>z# rj   z) configurationÚdescriptionÚ__doc__r|   TrI   r~   z#  Choices: %sz#  Default: %srl   r   r   z#  See also: rv   z# c.z = )r]   rm   r   rn   r/   Údefault_valuerU   rD   r^   rS   r„   r�   rr   Útyperƒ   Úsplit)r>   r‹   r<   ÚbreakerZparent_classesrŽ   r†   Údescr*   rt   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 ]ì\}}|jj }|js6q|d |j }d|v r^|d| ¡  7 }n|d| 7 }| |¡ z| ¡ }W n t	y–   d}Y n0 |durät
|ƒdkr¼|dd… d	 }| d
d¡}| td| ƒ¡ | d¡ |jpìd}| tt|ƒƒ¡ | d¡ qd |¡S )zwGenerate rST documentation for this class' config options.

        Excludes traits defined on parent classes.
        TrI   rv   r~   z : Nr   r€   ry   z\nz\\nzDefault: ``%s``r|   zNo descriptionrl   )r   r^   rn   rS   r7   r*   Zinfo_rstrD   r„   r…   r[   r�   r   rr   r   r]   )	r>   r†   Ú	classnamerp   rt   ÚttypeZtermlinerˆ   rr   r   r   r   Úclass_config_rst_doc¤  s2    



z!Configurable.class_config_rst_doc)NN)N)NN)N)N)r   r   r   r	   r   r'   r&   r1   ÚclassmethodrB   rE   r3   r   r   ra   rb   rs   ro   rŠ   r�   r™   rœ   Ú__classcell__r   r   r6   r   r    5   s6   H  ü5  ü8;r    c                   @  sX   e Zd ZdZeddd�Zedƒdddœd	d
„ƒZedƒddœdd„ƒZ	ddœdd„Z
dS )rX   z«A 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)rr   r!   rY   r   Ú
LoggerType)Úproposalr%   c                 C  sD   t |jtjtjfƒs6tj| jj› d|j› d�t	dd� t
 t|j¡S )Nz..log should be a Logger or LoggerAdapter, got rv   é   rM   )rT   ÚvalueÚloggingÚLoggerÚLoggerAdapterr   rO   r7   r   rP   ÚtÚcastrŸ   )r5   r    r   r   r   Ú_validate_logÚ  s    
ÿüz!LoggingConfigurable._validate_logr8   c                 C  s@   t | jtƒr,| jd usJ ‚t tj| jj¡S ddlm} | 	¡ S )Nr   )rY   )
rT   r&   rX   r¦   r§   r£   r¤   rY   Z	traitletsZ
get_logger)r5   rY   r   r   r   Ú_log_defaultæ  s
    z LoggingConfigurable._log_defaultzlogging.Handler | Nonec                 C  s@   | j s
dS t| j tjƒr| j n| j j}t|ddƒs6dS |jd S )z»Return 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   )rY   rT   r£   r¤   ÚloggerrU   rª   )r5   r«   r   r   r   Ú_get_log_handlerï  s    ÿz$LoggingConfigurable._get_log_handlerN)r   r   r   r’   r   rY   r   r¨   r   r©   r¬   r   r   r   r   rX   Ñ  s   rX   ÚCTÚSingletonConfigurable)Úboundc                   @  sb   e Zd ZdZdZeddœdd„ƒZeddœdd	„ƒZed
ddddœdd„ƒZeddœdd„ƒZ	dS )r®   zôA 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.
    Nz4t.Generator[type[SingletonConfigurable], None, None]r8   c                 c  s4   |   ¡ 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²   rT   Ú	_instancer°   r   r   r   Úclear_instance  s
    z$SingletonConfigurable.clear_instanceztype[CT]r"   r­   )r>   Úargsr$   r%   c                 O  s`   | j du r,| |i |¤Ž}|  ¡ D ]
}||_ q t| j | ƒr>| j S td| j› dt| j ƒj› �ƒ‚dS )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²   rT   r   r   r”   )r>   r¶   r$   rd   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®     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    rX   ÚTypeVarr­   r®   r   r   r   r   Ú<module>   s,   0	   1