o
    BZh	                     @  s|  d Z ddlm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lmZmZ ddlmZ ddl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mZm Z 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/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5 ddl6m7Z7 d8 Z9d8 Z:e;e	dsdge	_<dZ=ej>?ddZ@e@A dv rdZBne@A dv rdZBneCde@ e	jDoe	jDEdZFejGdejHdejIf d ZJejKejLd!f ZMej$eNejIf ZOejPej'eN  ZQej'ejRe  ZSd8d$d%ZTG d&d' d'eUZVG d(d) d)ejWZXG d*d+ d+eZYeYjZZ[eYj\Z]d9d:d2d3Z^d;d5d6Z_e`d7kr<eYa  dS dS )<z,A base class for a configurable application.    )annotationsN)OrderedDictdefaultdict)suppress)deepcopy)
dictConfig)dedent)ConfigurableSingletonConfigurable)ArgumentErrorConfigConfigFileNotFoundDeferredConfigStringJSONFileConfigLoaderKVArgParseConfigLoaderPyFileConfigLoader)
BoolDictEnumInstanceList
TraitErrorUnicodedefaultobserveobserve_compat)Bunch)nested_update)indentwrap_paragraphs   cast_unicode)import_itemz
The options below are convenience aliases to configurable class-options,
as listed in the "Equivalent to" description-line of the aliases.
To see all configurable class-options for some <cmd>, use:
    <cmd> --help-all
z
The command-line option below sets the respective configurable class-parameter:
    --Class.parameter=value
This line is evaluated in Python, so simple expressions are allowed.
For instance, to set `C.a=[0,1,2]`, you may type this:
    --C.a='range(3)'
argv zp
Subcommands are launched as `{app} cmd [args]`. For information on using
subcommand 'cmd', do: `{app} cmd -h`.
-TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR>   true1T>   r%   false0FzUnsupported value for environment variable: 'TRAITLETS_APPLICATION_RAISE_CONFIG_FILE_ERROR' is set to '%s' which is none of  {'0', '1', 'false', 'true', ''}.zpythonw.exeT.)boundzlogging.LoggerAdapter[t.Any]methodreturnc                   s$   t  d
 fdd}tt|S )a  Method decorator for catching invalid config (Trait/ArgumentErrors) during init.

    On a TraitError (generally caused by bad config), this will print the trait's
    message, and exit the app.

    For use on init methods, to prevent invoking excepthook on invalid input.
    appApplicationargst.Anykwargsr.   c              
     sl   z | g|R i |W S  t tfy5 } z| jd| | jd| j | d W Y d }~d S d }~ww )Nz0Bad config encountered during initialization: %szConfig at the time: %s   )r   r   logfataldebugconfigexit)r/   r1   r3   er-    S/var/www/html/lang_env/lib/python3.10/site-packages/traitlets/config/application.pyinners   s   z!catch_config_error.<locals>.innerN)r/   r0   r1   r2   r3   r2   r.   r2   )	functoolswrapstcastr+   )r-   r>   r<   r;   r=   catch_config_errorj   s   	rC   c                   @  s   e Zd ZdS )ApplicationErrorN)__name__
__module____qualname__r<   r<   r<   r=   rD      s    rD   c                      s,   e Zd ZdZejZdZd	 fddZ  Z	S )
LevelFormattera  Formatter with additional `highlevel` record

    This field is empty if log level is less than highlevel_limit,
    otherwise it is formatted with self.highlevel_format.

    Useful for adding 'WARNING' to warning messages,
    without adding 'INFO' to info, etc.
    z %(levelname)s |recordlogging.LogRecordr.   strc                   s.   |j | jkr| j|j |_nd|_t |S )Nr%   )levelnohighlevel_limithighlevel_format__dict__Z	highlevelsuperformat)selfrI   	__class__r<   r=   rQ      s   zLevelFormatter.format)rI   rJ   r.   rK   )
rE   rF   rG   __doc__loggingWARNrM   rN   rQ   __classcell__r<   r<   rS   r=   rH      s
    	rH   c                      s  e Zd ZU dZedZded< edZded< eeZded< ee	Z	ded< ee
Z
ded	< eZeZe Zded
< g Zded< 	ddddZedZded< e Zded< eeZedejddjddZeZedddjddZedd djddZ dd"d#Z!e"d$d%d&d'dd+d,Z#e"d-d.d/dd0d1Z$dd2d3Z%e&d-dd5d6Z'e(d7djddZ)d8d9iZ*d!ed:< d d&ej+iid;fd d<diid=fd d>diid?fd@Z,d!edA< e( Z-dBedC< e.dDddEZ/ee Z0e.e1dFi dGdZ2e Z3dHedI< edJdjddZ4edKdjddZ5e"d>ddLdMZ6e"d<ddNdOZ7ddRdSZ8e"dTe9d fdUdVZ:e;dddXdYZ<ddZd[Z=dd\d]Z>dd^d_Z?ddadbZ@ddcddZAddedfZBddgdhZCddidjZDddkdlZEddmdnZFddpdqZGdddsdtZHdddudvZIddxdyZJddzd{ZKdd|d}ZLdd~dZMdddZNdddZOe;ddddZPdddZQdddZReSddddZTeSdddZUe;ddddZVeS		rddddZWeXdddZYe;	ddddZZe;dddZ[	ddddZ\ddddZ]dddZ^ddddZ_dddZ`eSddddZa  ZbS )r0   z8A singleton application with full configuration support.Zapplicationzstr | Unicode[str, str | bytes]namezThis is an application.descriptionoption_descriptionkeyvalue_descriptionsubcommand_descriptionexamplesClassesTypeclassesNClassesType | Noner.   +t.Generator[type[Configurable], None, None]c                 c  sX    |du r| j }t }|D ]}t| D ]}t|tr(||vr(|| |V  qqdS )a  Iterate through configurable classes, including configurable parents

        :param classes:
            The list of classes to iterate; if not set, uses :attr:`classes`.

        Children should always be after parents, and each class should only be
        yielded once.
        N)r`   setreversedmro
issubclassr	   add)rR   r`   seencparentr<   r<   r=   _classes_inc_parents   s   
z Application._classes_inc_parentsz0.0versionzlist[str] | List[str]r$   )r   
         (   2   DEBUGINFOrW   ERRORCRITICALz#Set the log level by value or name.)default_valuehelpTr8   z%Y-%m-%d %H:%M:%Sz:The date format used by logging formatters for %(asctime)s)rw   z#[%(name)s]%(highlevel)s %(message)szThe Logging format templateStrDictc                 C  sl   ddddt | jddid| jj d| jj | j| jdi| jjddgd	id
d}t	r4|d= |d= |S )a  Return the base logging configuration.

        The default is to log to stderr using a StreamHandler, if no default
        handler already exists.

        The log handler level starts at logging.WARN, but this can be adjusted
        by setting the ``log_level`` attribute.

        The ``logging_config`` trait is merged into this allowing for finer
        control of logging.

        r4   consolezlogging.StreamHandlerzext://sys.stderr)class	formatterlevelstream.)r{   rQ   datefmtrr   )r}   handlersF)rl   r   
formattersloggersdisable_existing_loggersr   r   )
rV   getLevelName	log_level_log_formatter_clsrF   rE   
log_formatlog_datefmtrT   
IS_PYTHONWrR   r8   r<   r<   r=   get_default_logging_config   s6   
	
z&Application.get_default_logging_configr   r   r   logging_configchanger   Nonec                 C  s0   | j }t|trtttt|| _ |   d S N)	r   
isinstancerK   rA   rB   intgetattrrV   _configure_logging)rR   r   r   r<   r<   r=   _observe_logging_change  s   
z#Application._observe_logging_changer5   r   )typec                 C     |    d S r   )r   rR   r   r<   r<   r=   _observe_logging_default     z$Application._observe_logging_defaultc                 C  s*   |   }t|| jp
i  t| d| _d S )NT)r   r   r   r   _logging_configuredr   r<   r<   r=   r   !  s   
zApplication._configure_logging	AnyLoggerc                 C  sH   t | jj}d|_|}|dur"|jr|S |js	 |S |j}|dus|S )z#Start logging for this application.FN)rV   	getLoggerrT   rE   	propagater   rj   )rR   r5   _logr<   r<   r=   _log_default(  s   zApplication._log_defaulta!  
            Configure additional log handlers.

            The default stderr logs handler is configured by the
            log_level, log_datefmt and log_format settings.

            This configuration can be used to configure additional handlers
            (e.g. to output the log to a file) or for finer control over the
            default handlers.

            If provided this should be a logging configuration dictionary, for
            more information see:
            https://docs.python.org/3/library/logging.config.html#logging-config-dictschema

            This dictionary is merged with the base logging configuration which
            defines the following:

            * A logging formatter intended for interactive use called
              ``console``.
            * A logging handler that writes to stderr called
              ``console`` which uses the formatter ``console``.
            * A logger with the name of this application set to ``DEBUG``
              level.

            This example adds a new handler that writes to a file:

            .. code-block:: python

               c.Application.logging_config = {
                   "handlers": {
                       "file": {
                           "class": "logging.FileHandler",
                           "level": "DEBUG",
                           "filename": "<path/to/file>",
                       }
                   },
                   "loggers": {
                       "<application-name>": {
                           "level": "DEBUG",
                           # NOTE: if you don't list the default "console"
                           # handler here then it will be disabled
                           "handlers": ["console", "file"],
                       },
                   },
               }

        z	log-levelzApplication.log_levelaliasesz5Set log-level to debug, for the most verbose logging.show_configz<Show the application's configuration (human-readable format)show_config_jsonz2Show the application's configuration (json format))r7   zshow-configzshow-config-jsonflagsz#dict[str, t.Any] | Dict[str, t.Any]subcommandsz(traitlets.config.application.Application)
allow_noner<   zThe subset of our configuration that came from the command-line

        We re-load this configuration after loading config files,
        to ensure that it maintains highest priority.
        z	List[str]_loaded_config_fileszAInstead of starting the Application, dump configuration to stdoutzKInstead of starting the Application, dump configuration to stdout (as JSON)c                 C  s   |j | _d S r   )newr   r   r<   r<   r=   _show_config_json_changed  r   z%Application._show_config_json_changedc                 C  s   |j r| j| _| j| _d S d S r   )r   startZ_save_startstart_show_configr   r<   r<   r=   _show_config_changed  s   z Application._show_config_changedr3   r2   c                 K  sX   t j| fi | | j}|| jvr*| j|ju r |g| j| _d S | jd| j d S d S )Nr   )r
   __init__rT   r`   insert)rR   r3   clsr<   r<   r=   r     s   
zApplication.__init__r8   c                   s    t  | | jd|j d S )NzConfig changed: %r)rP   _config_changedr5   r7   r   r   rS   r<   r=   r     s   zApplication._config_changedArgvTypec                 C  s   |  | dS )zMDo the basic steps to configure me.

        Override in subclasses.
        N)parse_command_line)rR   r$   r<   r<   r=   
initialize  s   zApplication.initializec                 C  s(   | j durt| j tsJ | j  S dS )zAStart the app mainloop.

        Override in subclasses.
        N)subappr   r0   r   rR   r<   r<   r=   r     s   

zApplication.startc           
   
   C  s
  | j  }| j D ]}|j|v r"||j }|dd |dd q
| jr9tj|t	j
ddtd t	j
d dS | jrOtd | jD ]}td	|  qCt  t|D ]/}|| }|s\qSt| td
dd}t|D ]}|| }	td| dtj|	fi |  qjqSdS )z,start function used when show_config is Truer   Nr   r4   T)r   	sort_keysr   
zLoaded config files:z     )r   compactz  .z = )r8   copyrT   re   rE   popr   jsondumpsysstdoutreprwriter   printsorteddictpprintpformat)
rR   r8   r   Z
cls_configf	classnameZclass_configZpformat_kwargs	traitnamevaluer<   r<   r=   r     s6   



$zApplication.start_show_configc                 C     t d|   dS )z"Print the alias parts of the help.r   N)r   joinemit_alias_helpr   r<   r<   r=   print_alias_help     zApplication.print_alias_helpt.Generator[str, None, None]c                 c  sT   | j sdS i }| jD ]}| dd D ]}ttjt |||j< qq| j  D ]}\}}zdt	|t
r9|\}}nd}|ddd \}}|d | }|| }|jdd| }	|j|	|d }
t	|t
si|f}t|td}d	d
d |D }|
d d| ||
d< |
E dH  td| V  W q* ty } z	| jd||  d}~ww dS )z+Yield the lines for alias part of the help.Nr   Trx   )Zhelptextkey, c                 s  (    | ]}t |d krdnd| V  qdS r4   z--%sz-%sNlen.0mr<   r<   r=   	<genexpr>     & z.Application.emit_alias_help.<locals>.<genexpr>r   --zEquivalent to: [--%s]z7Failed collecting help-message for alias %r, due to: %s)r   r`   re   rA   rB   Typer	   rE   itemsr   tuplesplitZclass_traitsZclass_get_trait_help
splitlinesr   r   r   replacer   	Exceptionr5   error)rR   	classdictr   ri   aliaslongnamefhelpr   r   traitZfhelp_linesexr<   r<   r=   r     s>   




zApplication.emit_alias_helpc                 C  r   )z Print the flag part of the help.r   N)r   r   emit_flag_helpr   r<   r<   r=   print_flag_help'  r   zApplication.print_flag_helpc                 c  s    | j sdS | j  D ]X\}\}}z=t|ts|f}t|td}ddd |D }|V  tt|	 V  ddd | D }d| }tt|V  W q t
yc } z	| jd	||  d}~ww dS )
z.Yield the lines for the flag part of the help.Nr   r   c                 s  r   r   r   r   r<   r<   r=   r   5  r   z-Application.emit_flag_help.<locals>.<genexpr> c                 s  s<    | ]\}}|  D ]\}}d | d| d| V  q
qdS )r   r   =N)r   )r   ZclnameZ
props_dictpropvalr<   r<   r=   r   8  s    zEquivalent to: [%s]z6Failed collecting help-message for flag %r, due to: %s)r   r   r   r   r   r   r   r   r   stripr   r5   r   )rR   r   cfgr   Zcfg_listZcfg_txtr   r<   r<   r=   r   +  s,   

zApplication.emit_flag_helpc                 C  r   )z#Print the options part of the help.r   N)r   r   emit_options_helpr   r<   r<   r=   print_optionsC  r   zApplication.print_optionsc                 c  sl    | j s	| js	dS d}|V  dt| V  t| jD ]}|V  dV  q|  E dH  |  E dH  dV  dS )z1Yield the lines for the options part of the help.NOptionsr   r%   )r   r   r   r   r[   r   r   )rR   headerpr<   r<   r=   r   G  s   
zApplication.emit_options_helpc                 C  r   )z&Print the subcommand part of the help.r   N)r   r   emit_subcommands_helpr   r<   r<   r=   print_subcommandsV  r   zApplication.print_subcommandsc                 c  s    | j sdS d}|V  dt| V  t| jj| jdD ]}|V  dV  q| j  D ]\}\}}|V  |r>tt|	 V  q*dV  dS )z4Yield the lines for the subcommand part of the help.NZSubcommandsr   )r/   r%   )
r   r   r   r]   rQ   rY   r   r   r   r   )rR   r   r   subc_rw   r<   r<   r=   r   Z  s   
z!Application.emit_subcommands_helpboolc                 c  s    |sdV  dV  dS dS )zzYield the very bottom lines of the help message.

        If classes=False (the default), print `--help-all` msg.
        z5To see all available configurables, use `--help-all`.r%   Nr<   rR   r`   r<   r<   r=   emit_help_epiloguek  s
   
zApplication.emit_help_epilogueFc                 C  s   t d| j|d dS )zPrint the help for each Configurable class in self.classes.

        If classes=False (the default), only flags and aliases are printed.
        r   r`   N)r   r   	emit_helpr   r<   r<   r=   
print_helpt  s   zApplication.print_helpc                 c  s    |   E dH  |  E dH  |  E dH  |rA|  }|dur4dV  dV  t| jD ]}|V  dV  q+|D ]
}| V  dV  q6|  E dH  | |E dH  dS )zYield the help-lines for each Configurable class in self.classes.

        If classes=False (the default), only flags and aliases are printed.
        NzClass optionsz=============r%   )	emit_descriptionr   r   _classes_with_config_traitsr   r\   Zclass_get_helpemit_examplesr  )rR   r`   Zhelp_classesr   r   r<   r<   r=   r  {  s"   
zApplication.emit_helprK   c                 C  s   d dd |  D S )zwGenerate rST format documentation for the config options this application

        Returns a multiline string.
        r   c                 s  s    | ]}|  V  qd S r   )Zclass_config_rst_doc)r   ri   r<   r<   r=   r         z6Application.document_config_options.<locals>.<genexpr>)r   rk   r   r<   r<   r=   document_config_options  s   z#Application.document_config_optionsc                 C  r   )z"Print the application description.r   N)r   r   r  r   r<   r<   r=   print_description  r   zApplication.print_descriptionc                 c  s,    t | jp	| jp	dD ]}|V  dV  qdS )z-Yield lines with the application description.r%   N)r   rZ   rU   )rR   r   r<   r<   r=   r    s
   zApplication.emit_descriptionc                 C  r   )z1Print usage and examples (see `emit_examples()`).r   N)r   r   r  r   r<   r<   r=   print_examples  r   zApplication.print_examplesc                 c  s<    | j rdV  dV  dV  tt| j  V  dV  dS dS )zYield lines with the usage and examples.

        This usage string goes at the end of the command line help string
        and should contain examples of the application's usage.
        ZExamplesz--------r%   N)r^   r   r   r   r   r<   r<   r=   r    s   
zApplication.emit_examplesc                 C  s   t | j dS )zPrint the version string.N)r   rl   r   r<   r<   r=   print_version  s   zApplication.print_versionr   c                 C  s   | j |}|dusJ |\}}t|trt|}t|tr0t|tr0| j	  |j
| d| _nt|r:|| | _ntd| | j| dS )z"Initialize a subcommand with argv.N)rj   z%Invalid mappings for subcommand '%s'!)r   getr   rK   r#   r   rf   r0   rT   Zclear_instanceinstancer   callableAssertionErrorr   )rR   r   r$   r   r   r   r<   r<   r=   initialize_subcommand  s   

z!Application.initialize_subcommand)tuple[dict[str, t.Any], dict[str, t.Any]]c                 C  s^  t t}| jD ]}|j}| dd D ]
}||j | qqi }| j D ]9\}}t|t	r4|\}}|
dd\}}	|| }
t|
dkrJ|
d }t|t	sR|f}|D ]}d||	g||< qTq'i }| j D ]B\}\}}i }| D ]"\}}|| }
t|
dkr|
d }||v r|| | qt|||< qtt|t	s|f}|D ]}||f||< qqh||fS )a  Flatten flags and aliases for loaders, so cl-args override as expected.

        This prevents issues such as an alias pointing to InteractiveShell,
        but a config file setting the same trait in TerminalInteraciveShell
        getting inappropriate priority over the command-line arg.
        Also, loaders expect ``(key: longname)`` and not ``key: (longname, help)`` items.

        Only aliases with exactly one descendent in the class list
        will be promoted.

        r4   r   r   r   )r   listr`   rE   re   appendr   r   r   r   r   r   r   r   update)rR   Zmro_treer   clsnamerj   r   r   r   r   r   childrenalr   r   Zflagdictrw   ZnewflagZsubdictkr<   r<   r=   flatten_flags  sF   




zApplication.flatten_flagslist[str] | Noner   c                 C  s   t ||||| j| jdS )N)r`   r5   r   )r   r5   r   )rR   r$   r   r   r`   r<   r<   r=   _create_loader  s   zApplication._create_loadercheck_argcomplete	list[str]c              	   C  sT   |r'dt jv r'zddlm} | }|dusJ |W S  ttfy&   Y tjS w tjS )a  Get `sys.argv` or equivalent from `argcomplete`

        `argcomplete`'s strategy is to call the python script with no arguments,
        so ``len(sys.argv) == 1``, and run until the `ArgumentParser` is constructed
        and determine what completions are available.

        On the other hand, `traitlet`'s subcommand-handling strategy is to check
        ``sys.argv[1]`` and see if it matches a subcommand, and if so then dynamically
        load the subcommand app and initialize it with ``sys.argv[1:]``.

        This helper method helps to take the current tokens for `argcomplete` and pass
        them through as `argv`.
        _ARGCOMPLETEr   )get_argcomplete_cwordsN)osenviron#traitlets.config.argcomplete_configr   ImportErrorModuleNotFoundErrorr   r$   )r   r  r   cwordsr<   r<   r=   _get_sys_argv  s   zApplication._get_sys_argvc              	   C  s@   dt jvrdS zddlm} |  W dS  ttfy   Y dS w )a  Helper for `argcomplete` to recognize `traitlets` subcommands

        `argcomplete` does not know that `traitlets` has already consumed subcommands,
        as it only "sees" the final `argparse.ArgumentParser` that is constructed.
        (Indeed `KVArgParseConfigLoader` does not get passed subcommands at all currently.)
        We explicitly manipulate the environment variables used internally by `argcomplete`
        to get it to skip over the subcommand tokens.
        r  Nr   )increment_argcomplete_index)r!  r"  r#  r(  r$  r%  )r   r(  r<   r<   r=   "_handle_argcomplete_for_subcommand3  s   

z.Application._handle_argcomplete_for_subcommandc                   s  t |trJ |du r| jt| jddd }dd |D | _|r1|d dkr1|dd dg }| jrZt|dkrZ|d |dd }}td	|rZ|| jv rZ| 	  | 
||S z|d|d
  W n typ   | Y nw t fdddD r| d v  | d d v sd v r|   | d |  \}}t|  }| j||||d}z	t| | _W n ty    w | | j |j| _dS )z!Parse the command line arguments.N)r  r4   c                 S  s   g | ]}t |qS r<   r!   )r   argr<   r<   r=   
<listcomp>M  s    z2Application.parse_command_line.<locals>.<listcomp>r   rw   -hz^\w(\-?\w)*$r   c                 3  s    | ]}| v V  qd S r   r<   )r   xZinterpreted_argvr<   r=   r   d  r  z1Application.parse_command_line.<locals>.<genexpr>)r,  
--help-allz--helpr/  z	--versionz-Vr  )r   rK   r'  r   r   r$   r   rematchr)  r  index
ValueErroranyr  r9   r  r  r  r  r  r   load_config
cli_config
SystemExitupdate_config
extra_args)rR   r$   r   Zsubargvr   r   r`   loaderr<   r.  r=   r   G  s@   

zApplication.parse_command_linebasefilenamepath#str | t.Sequence[str | None] | NoneAnyLogger | Noneraise_config_file_errorst.Generator[t.Any, None, None]c                 c  sZ   t |ts
|du r|g}t|D ]}| j|d ||d}|r*|d||p(t  | j|d ||d}g }g }	||fD ]m}
d}z|
 }W n# t	yO   Y n$ t
yi   |
jpY|}|r] |rg|jd|dd Y n
w |rs|d	|
j |rt|	|D ]\}}||}|r|r|d
||
jtj|dd qz||
jfV  || |	|
j q<qdS )zeLoad config files (py,json) by filename and path.

        yield each config object in turn.
        Nz.py)r<  r5   zLooking for %s in %sz.jsonz&Exception while loading config file %sT)exc_infozLoaded config file: %szMCollisions detected in {0} and {1} config files. {1} has higher priority: {2}r    )r   )r   rK   rd   python_config_loader_classr7   r!  getcwdjson_config_loader_classr5  r   r   Zfull_filenamer   zip
collisionswarningrQ   r   dumpsr  )r   r;  r<  r5   r?  currentZpyloaderZ
jsonloaderZloaded	filenamesr:  r8   filenameZearlier_configrF  r<   r<   r=   _load_config_filesz  sZ   



zApplication._load_config_filesc                 C  s   | j dd S )z$Currently loaded configuration filesN)r   r   r<   r<   r=   loaded_config_files  s   zApplication.loaded_config_filesrK  c                 C  sp   t j|\}}t }| j||| j| jdD ]\}}|| || jvr*| j	| q|| j
 | | dS )z'Load config files by filename and path.)r<  r5   r?  N)r!  r<  splitextr   rL  r5   r?  merger   r  r6  r8  )rR   rK  r<  ext
new_configr8   fnamer<   r<   r=   load_config_file  s   

zApplication.load_config_filec           
      C  s   | j  dd}t }| jd| tj D ]-\}}|	|rE| jd|| |
d^}}}|}|D ]}	||	 }q6t||t| q|| j | | dS )z!Load config files by environment.-r   z1Looping through config variables with prefix "%s"zSeeing environ "%s"="%s"__N)rY   upperr   r   r5   r7   r!  r"  r   
startswithr   setattrr   rO  r6  r8  )
rR   ZPREFIXrQ  r  vr   r<  r   sectionr   r<   r<   r=   load_config_environ  s   

zApplication.load_config_environc                 #  s    |du r| j }tdd | |D  d fdd		   }tfdd  D   |kr2nq  D ]	\}}|r@|V  q7dS )a  
        Yields only classes with configurable traits, and their subclasses.

        :param classes:
            The list of classes to iterate; if not set, uses :attr:`classes`.

        Thus, produced sample config-file will contain all classes
        on which a trait-value may be overridden:

        - either on the class owning the trait,
        - or on its subclasses, even if those subclasses do not define
          any traits themselves.
        Nc                 s  s$    | ]}|t |jd dfV  qdS )Trx   N)r   Zclass_own_traits)r   r   r<   r<   r=   r     s
    
z:Application._classes_with_config_traits.<locals>.<genexpr>r   r2   r.   r   c                   s   t  fdd| jD S )Nc                 3  s     | ]}| v o | V  qd S r   r<   )r   bcls_to_configr<   r=   r     s    zZApplication._classes_with_config_traits.<locals>.is_any_parent_included.<locals>.<genexpr>)r4  	__bases__)r   r]  r<   r=   is_any_parent_included  s   zGApplication._classes_with_config_traits.<locals>.is_any_parent_includedTc                 3  s$    | ]\}}||p |fV  qd S r   r<   )r   r   inc_yes)r`  r<   r=   r     s
    
)r   r2   r.   r   )r`   r   rk   r   r   )rR   r`   Zto_incl_origclra  r<   )r^  r`  r=   r    s(   z'Application._classes_with_config_traitsc                 C  sn   d| j  g}|d |d |d |du r| jn|}t| |}|D ]
}||| q'd|S )z/generate default config file from Configurablesz# Configuration file for %s.r%   zc = get_config()  #noqaNr   )rY   r  r`   r  r  Zclass_config_sectionr   )rR   r`   linesZconfig_classesr   r<   r<   r=   generate_config_file  s   



z Application.generate_config_filec              	   C  sX   t | ddr*| jjD ]}tt |  W d    n1 sw   Y  q
d| _d S d S )Nr   F)r   r5   r   r   r   closer   )rR   handlerr<   r<   r=   close_handlers  s   


zApplication.close_handlersr   exit_statusint | str | Nonec                 C  s&   | j d| j |   t| d S )NzExiting application: %s)r5   r7   rY   rg  r   r9   )rR   rh  r<   r<   r=   r9   #  s   zApplication.exitc                 C  r   r   )rg  r   r<   r<   r=   __del__(  s   zApplication.__del__c                 K  s&   | j di |}|| |  dS )zLaunch a global instance of this Application

        If a global instance already exists, this reinitializes and starts it
        Nr<   )r  r   r   )r   r$   r3   r/   r<   r<   r=   launch_instance+  s   
zApplication.launch_instancer   )r`   ra   r.   rb   )r.   ry   )r   r   r.   r   )r.   r   )r.   r   )r3   r2   r.   r   )r$   r   r.   r   )r.   r   )r`   r   r.   r   )F)r`   r   r.   r   )r.   rK   )r   rK   r$   r   r.   r   )r.   r  )
r$   r  r   ry   r   ry   r`   ra   r.   r   )r  r   r.   r  )NF)
r;  rK   r<  r=  r5   r>  r?  r   r.   r@  )r.   r  )rK  rK   r<  r=  r.   r   )r`   ra   r.   rK   )r   )rh  ri  r.   r   )r$   r   r3   r2   r.   r   )crE   rF   rG   rU   r   rY   __annotations__rZ   r[   r\   r]   r   rB  r   rD  r^   r`   rk   rl   r   r$   r   r&   r?  r   rV   rW   tagr   rH   r   r   r   r   r   r   r   r   r   r   r   r   r   rr   r   r   r   r   r9  r   r6  r   r   r   r   r   r   r   r   rC   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r	  r
  r  r  r  r  r  r  r  classmethodr'  r)  r   rL  propertyrM  rS  r[  r  rd  rg  r9   rj  rk  rX   r<   r<   rS   r=   r0      s$  
 
3

07	

 



	
!

&





	







;27*


r0   rY   rK   configurableset_help
unset_helpry   c                 C  sV   |pd| }|pd| }| d\}}||dii}||dii}| ||fd|  ||fiS )a  Helper for building basic --trait, --no-trait flags.

    Parameters
    ----------
    name : str
        The name of the flag.
    configurable : str
        The 'Class.trait' string of the trait to be set/unset with the flag
    set_help : unicode
        help string for --name flag
    unset_help : unicode
        help string for --no-name flag

    Returns
    -------
    cfg : dict
        A dict with two keys: 'name', and 'no-name', for setting and unsetting
        the trait, respectively.
    zset %s=Truezset %s=Falser   TFzno-)r   )rY   rp  rq  rr  r   r   setterZunsetterr<   r<   r=   boolean_flag>  s   rt  r   c                   C  s   t  r	t  jS t S )z|Get the config object for the global Application instance, if there is one

    otherwise return an empty config object
    )r0   Zinitializedr  r8   r   r<   r<   r<   r=   
get_config]  s   
ru  __main__)r-   r+   r.   r+   )r%   r%   )
rY   rK   rp  rK   rq  rK   rr  rK   r.   ry   )r.   r   )brU   
__future__r   r?   r   rV   r!  r   r0  r   typingrA   collectionsr   r   
contextlibr   r   r   logging.configr   textwrapr   Ztraitlets.config.configurabler	   r
   Ztraitlets.config.loaderr   r   r   r   r   r   r   Ztraitlets.traitletsr   r   r   r   r   r   r   r   r   r   Ztraitlets.utils.bunchr   Ztraitlets.utils.nested_updater   Ztraitlets.utils.textr   r   utilsr"   Zutils.importstringr#   r   r[   r\   hasattrr$   r]   r"  r  Z_envvarlowerr&   r3  
executableendswithr   TypeVarCallableAnyr+   UnionLoggerr   rK   ry   Optionalr   r   r_   rC   r   rD   	FormatterrH   r0   r   Zdefault_aliasesr   Zdefault_flagsrt  ru  rE   rk  r<   r<   r<   r=   <module>   s    $0	


       )

