o
    HTh	                     @  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>   1trueT>   r%   0falseFzUnsupported 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-    _/home/air/segue/gemini/backup/venv/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__	highlevelsuperformat)selfrI   	__class__r<   r=   rR      s   zLevelFormatter.format)rI   rJ   r.   rK   )
rE   rF   rG   __doc__loggingWARNrM   rN   rR   __classcell__r<   r<   rT   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.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)rb   setreversedmro
issubclassr	   add)rS   rb   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INFOrX   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)ry   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}   rR   datefmtrt   )r   handlersF)rn   r   
formattersloggersdisable_existing_loggersr   r   )
rW   getLevelName	log_level_log_formatter_clsrF   rE   
log_formatlog_datefmtrU   
IS_PYTHONWrS   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getattrrW   _configure_logging)rS   r   r   r<   r<   r=   _observe_logging_change  s   
z#Application._observe_logging_changer5   r   )typec                 C     |    d S r   )r   rS   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)rW   	getLoggerrU   rE   	propagater   rl   )rS   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   start_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__rU   rb   insert)rS   r3   clsr<   r<   r=   r     s   
zApplication.__init__r8   c                   s    t  | | jd|j d S )NzConfig changed: %r)rQ   _config_changedr5   r7   r   r   rT   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)rS   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   rS   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   copyrU   rg   rE   popr   jsondumpsysstdoutreprwriter   printsorteddictpprintpformat)
rS   r8   r   
cls_configf	classnameclass_config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   Trz   )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   rb   rg   rA   rB   Typer	   rE   itemsr   tuplesplitclass_traitsclass_get_trait_help
splitlinesr   r   r   replacer   	Exceptionr5   error)rS   	classdictr   rk   aliaslongnamefhelpr   r   trait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   clname
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   )rS   r   cfgr   cfg_list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   )rS   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.NSubcommandsr   )r/   r%   )
r   r   r   r_   rR   r[   r   r   r   r   )rS   r  r  subc_ry   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<   rS   rb   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   rb   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^   class_get_helpemit_examplesr  )rS   rb   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   )class_config_rst_doc)r   rk   r<   r<   r=   r         z6Application.document_config_options.<locals>.<genexpr>)r   rm   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   r\   rV   )rS   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.
        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   rn   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)rl   z%Invalid mappings for subcommand '%s'!)r   getr   rK   r#   r   rh   r0   rU   clear_instanceinstancer   callableAssertionErrorr   )rS   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   listrb   rE   rg   appendr   r   r   r   r   r   r   r   update)rS   mro_treer   clsnamerl   r   r   r   r  r   childrenalr   r   flagdictry   newflagsubdictkr<   r<   r=   flatten_flags  sF   




zApplication.flatten_flagslist[str] | Noner   c                 C  s   t ||||| j| jdS )N)rb   r5   r   )r   r5   r   )rS   r$   r   r   rb   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_configr8  ImportErrorModuleNotFoundErrorr   r$   )r   r5  r8  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.
        r7  Nr   )increment_argcomplete_index)r9  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)r5  r4   c                 S  s   g | ]}t |qS r<   r!   )r   argr<   r<   r=   
<listcomp>M  s    z2Application.parse_command_line.<locals>.<listcomp>r   ry   -hz^\w(\-?\w)*$r   c                 3  s    | ]}| v V  qd S r   r<   )r   xinterpreted_argvr<   r=   r   d  r  z1Application.parse_command_line.<locals>.<genexpr>)rD  
--help-allz--helprH  z	--versionz-Vr  )r   rK   r?  r  r   r$   r   rematchrA  r%  index
ValueErroranyr  r9   r  r2  r'  r  r4  r   load_config
cli_config
SystemExitupdate_config
extra_args)rS   r$   r  subargvr   r   rb   loaderr<   rF  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)rV  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   rf   python_config_loader_classr7   r9  getcwdjson_config_loader_classrN  r   r   full_filenamer   zip
collisionswarningrR   r   dumpsr(  )r   rU  rV  r5   rY  currentpyloader
jsonloaderloaded	filenamesrT  r8   filenameearlier_configra  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_filesri  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.)rV  r5   rY  N)r9  rV  splitextr   rk  r5   rY  merger   r(  rO  rQ  )rS   ri  rV  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)r[   upperr   r   r5   r7   r9  r:  r   
startswithr   setattrr   rn  rO  rQ  )
rS   PREFIXrp  r1  vr  rV  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 )Trz   N)r  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>)rM  	__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  )rb   r   rm   r   r   )rS   rb   to_incl_origclr  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   )r[   r(  rb   r'  r  class_config_sectionr   )rS   rb   lines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   )rS   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   r[   r  r   r9   )rS   r  r<   r<   r=   r9   #  s   zApplication.exitc                 C  r   r   )r  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   )rb   rc   r.   rd   )r.   r{   )r   r   r.   r   )r.   r   )r.   r   )r3   r2   r.   r   )r$   r   r.   r   )r.   r   )rb   r  r.   r   )F)rb   r  r.   r   )r.   rK   )r  rK   r$   r   r.   r   )r.   r&  )
r$   r3  r   r{   r   r{   rb   rc   r.   r   )r5  r  r.   r6  )NF)
rU  rK   rV  rW  r5   rX  rY  r  r.   rZ  )r.   r6  )ri  rK   rV  rW  r.   r   )rb   rc   r.   rK   )r   )r  r  r.   r   )r$   r   r3   r2   r.   r   )crE   rF   rG   rV   r   r[   __annotations__r\   r]   r^   r_   r   r\  r   r^  r`   rb   rm   rn   r   r$   r   r&   rY  r   rW   rX   tagr   rH   r   r   r   r   r   r   r   r   r   r   r   r   r   rt   r   r   r   r   rR  r   rO  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%  r2  r4  classmethodr?  rA  r   rk  propertyrl  rr  r{  r  r  r  r9   r  r  rY   r<   r<   rT   r=   r0      s$  
 
3

07	

 



	
!

&





	







;27*


r0   r[   rK   configurableset_help
unset_helpr{   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   )r[   r  r  r  r   r   setterunsetterr<   r<   r=   boolean_flag>  s   r  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   initializedr"  r8   r   r<   r<   r<   r=   
get_config]  s   
r  __main__)r-   r+   r.   r+   )r%   r%   )
r[   rK   r  rK   r  rK   r  rK   r.   r{   )r.   r   )brV   
__future__r   r?   r   rW   r9  r   rI  r   typingrA   collectionsr   r   
contextlibr   r   r   logging.configr   textwrapr   traitlets.config.configurabler	   r
   traitlets.config.loaderr   r   r   r   r   r   r   traitlets.traitletsr   r   r   r   r   r   r   r   r   r   traitlets.utils.bunchr   traitlets.utils.nested_updater   traitlets.utils.textr   r   utilsr"   utils.importstringr#   r   r]   r^   hasattrr$   r_   r:  r   _envvarlowerr&   rL  
executableendswithr   TypeVarCallableAnyr+   UnionLoggerr   rK   r{   Optionalr   r   ra   rC   r   rD   	FormatterrH   r0   r   default_aliasesr   default_flagsr  r  rE   r  r<   r<   r<   r=   <module>   s    $0	

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