U
    -e                     @  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  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l0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6 d7 Z8d7 Z9e:e	dsTdge	_;dZ<ej=>ddZ?e?@ dkrzdZAn e?@ dkrdZAneBde? e	jCoe	jCDdZEejFdejGdejHf d ZIejJejKejLf ZMej#eNejHf ZOejPej&eN  ZQej&ejRe  ZSddd!d"d#ZTG d$d% d%eUZVG d&d' d'ejWZXG d(d) d)eZYeYjZZ[eYj\Z]d4d*d*d*d*d+d,d-d.Z^d/d0d1d2Z_e`d3kreYa  dS )5z,A base class for a configurable application.    )annotationsN)OrderedDictdefaultdict)suppress)deepcopy)
dictConfig)dedent)ConfigurableSingletonConfigurable)ArgumentErrorConfigConfigFileNotFound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.)bound)methodreturnc                   s.   t  dddd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.
    Applicationt.Any)appargskwargsr-   c              
     sf   z | f||W S  t tfk
r` } z,| jd| | jd| j | d W 5 d }~X Y nX d S )Nz0Bad config encountered during initialization: %szConfig at the time: %s   )r   r   logfataldebugconfigexit)r0   r1   r2   er,    ]/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/traitlets/config/application.pyinnerr   s    z!catch_config_error.<locals>.inner)	functoolswrapstcastr*   )r,   r=   r;   r:   r<   catch_config_errori   s    	rB   c                   @  s   e Zd ZdS )ApplicationErrorN)__name__
__module____qualname__r;   r;   r;   r<   rC   ~   s   rC   c                      s2   e Zd ZdZejZdZdd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 |zlogging.LogRecordstr)recordr-   c                   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<   rO      s    zLevelFormatter.format)
rD   rE   rF   __doc__loggingWARNrK   rL   rO   __classcell__r;   r;   rQ   r<   rG      s   	rG   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< ddddddZedZded< e Z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 dd d!d"Z!e"d#d$d%d&d'd(d)d*d+Z#e"d,d-d.d'd(d)d/d0Z$d(d d1d2Z%e&d,d3d d4d5Z'e(d6djddZ)d7d8iZ*ded9< 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d@< e( Z-dAedB< e.dCddDZ/ee Z0e.e1dEi dFdZ2e Z3edGdjddZ4edHdjddZ5e"d=d'd(d)dIdJZ6e"d;d'd(d)dKdLZ7dMd(dNdOdPZ8e"dQe9d'd(d) fdRdSZ:e;ddTd(dUdVdWZ<d(d dXdYZ=d(d dZd[Z>d(d d\d]Z?d^d d_d`Z@d(d dadbZAd^d dcddZBd(d dedfZCd^d dgdhZDd(d didjZEd^d dkdlZFdmd^ddndoZGddmd(ddqdrZHddmd^ddsdtZIdud dvdwZJd(d dxdyZKd^d dzd{ZLd(d d|d}ZMd^d d~dZNd(d ddZOe;ddudTd(dddZPdd ddZQddddddddZReSddmddddZTeSd(d ddZUe;ddTd(dUddZVeSddudddmddddZWeXdd ddZYe;ddudd(dddZZddddddZ[dddudddZ\d(d ddZ]ddd(dddZ^d(d ddZ_eSddTdMd(dddZ`  ZaS )r.   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classesNzClassesType | Nonez+t.Generator[type[Configurable], None, None])r^   r-   c                 c  sV   |dkr| j }t }|D ]8}t| D ]&}t|tr(||k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)rP   r^   seencparentr;   r;   r<   _classes_inc_parents   s    
z Application._classes_inc_parentsz0.0version)r   
         (   2   DEBUGINFOrU   ERRORCRITICALz#Set the log level by value or name.)default_valuehelpTr7   z%Y-%m-%d %H:%M:%Sz:The date format used by logging formatters for %(asctime)s)rs   z#[%(name)s]%(highlevel)s %(message)szThe Logging format templateStrDictr-   c                 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	rh|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.

        r3   consolezlogging.StreamHandlerzext://sys.stderr)class	formatterlevelstream.)rx   rO   datefmtrn   )rz   handlersF)rh   r~   
formattersloggersdisable_existing_loggersr~   r   )
rT   getLevelName	log_level_log_formatter_clsrE   rD   
log_formatlog_datefmtrR   
IS_PYTHONWrP   r7   r;   r;   r<   get_default_logging_config   s2    
	z&Application.get_default_logging_configr   r   r   logging_configr   None)changer-   c                 C  s(   | j }t|trtt|| _ |   d S N)r   
isinstancerH   getattrrT   _configure_logging)rP   r   r   r;   r;   r<   _observe_logging_change  s    
z#Application._observe_logging_changer4   r   )typec                 C  s   |    d S r   )r   rP   r   r;   r;   r<   _observe_logging_default  s    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  s<   t | jj}d|_|}|r8|jr&|S |js0q8q|j}q|S )z#Start logging for this application.F)rT   	getLoggerrR   rD   	propagater~   rf   )rP   r4   _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))r6   zshow-configzshow-config-jsonflagszdict[str, t.Any] | Dict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.
        zAInstead 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  s    z%Application._show_config_json_changedc                 C  s   |j r| j| _| j| _d S r   )r   startZ_save_startstart_show_configr   r;   r;   r<   _show_config_changed  s    z Application._show_config_changedr/   )r2   r-   c                 K  sN   t j| f| | j}|| jkrJ| j|jkr:|f| j| _n| jd| j d S )Nr   )r
   __init__rR   r^   insert)rP   r2   clsr;   r;   r<   r     s    
zApplication.__init__r7   c                   s    t  | | jd|j d S )NzConfig changed: %r)rN   _config_changedr4   r6   r   r   rQ   r;   r<   r     s    zApplication._config_changedArgvType)r#   r-   c                 C  s   |  | dS )zMDo the basic steps to configure me.

        Override in subclasses.
        N)parse_command_line)rP   r#   r;   r;   r<   
initialize  s    zApplication.initializec                 C  s(   | j dk	r$t| j tst| j  S dS )zAStart the app mainloop.

        Override in subclasses.
        N)subappr   r.   AssertionErrorr   rP   r;   r;   r<   r     s    
zApplication.startc           
   	   C  s  | j  }| j D ]0}|j|kr||j }|dd |dd q| jrrtj|t	j
ddtd t	j
d dS | jrtd | jD ]}td	|  qt  t|D ]Z}|| }|sqt| td
dd}t|D ]*}|| }	td| dtj|	f|  qqdS )z,start function used when show_config is Truer   Nr   r3   T)r   	sort_keysr   
zLoaded config files:z     )r   compactz  .z = )r7   copyrR   ra   rD   popr   jsondumpsysstdoutreprwrite_loaded_config_filesprintsorteddictpprintpformat)
rP   r7   r   Z
cls_configf	classnameZclass_configZpformat_kwargs	traitnamevaluer;   r;   r<   r     s0    



zApplication.start_show_configc                 C  s   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  s    zApplication.print_alias_helpzt.Generator[str, None, None]c                 c  sb  | j s
dS i }| jD ]2}| dd D ]}ttjt |||j< q(q| j  D ]\}}zt	|t
rr|\}}nd}|ddd \}}|d | }|| }|jdd| }	|j|	|d }
t	|t
s|f}t|td}d	d
d |D }|
d d| ||
d< |
E dH  td| V  W qR tk
rZ } z| jd||  W 5 d}~X Y qRX qRdS )z+Yield the lines for alias part of the help.Nr|   Trt   )Zhelptextkey, c                 s  s&   | ]}t |d krdnd| V  qdS r3   z--%sz-%sNlen.0mr;   r;   r<   	<genexpr>  s     z.Application.emit_alias_help.<locals>.<genexpr>r   --zEquivalent to: [--%s]z7Failed collecting help-message for alias %r, due to: %s)r   r^   ra   r@   rA   Typer	   rD   itemsr   tuplesplitZclass_traitsZclass_get_trait_help
splitlinesr   r   r   replacer   	Exceptionr4   error)rP   	classdictr   re   aliaslongnamefhelpr   r   traitZfhelp_linesexr;   r;   r<   r     s4    




zApplication.emit_alias_helpc                 C  s   t d|   dS )z Print the flag part of the help.r   N)r   r   emit_flag_helpr   r;   r;   r<   print_flag_help'  s    zApplication.print_flag_helpc                 c  s   | j s
dS | j  D ]\}\}}zzt|ts2|f}t|td}ddd |D }|V  tt|	 V  ddd | D }d| }tt|V  W q t
k
r } z| jd	||  W 5 d}~X Y qX qdS )
z.Yield the lines for the flag part of the help.Nr   r   c                 s  s&   | ]}t |d krdnd| V  qdS r   r   r   r;   r;   r<   r   5  s     z-Application.emit_flag_help.<locals>.<genexpr> c                 s  s:   | ]2\}}|  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   r4   r   )rP   r   cfgr   Zcfg_listZcfg_txtr   r;   r;   r<   r   +  s$    

zApplication.emit_flag_helpc                 C  s   t d|   dS )z#Print the options part of the help.r   N)r   r   emit_options_helpr   r;   r;   r<   print_optionsC  s    zApplication.print_optionsc                 c  sj   | j s| jsdS d}|V  dt| V  t| jD ]}|V  dV  q2|  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   rY   r   r   )rP   headerpr;   r;   r<   r   G  s    zApplication.emit_options_helpc                 C  s   t d|   dS )z&Print the subcommand part of the help.r   N)r   r   emit_subcommands_helpr   r;   r;   r<   print_subcommandsV  s    zApplication.print_subcommandsc                 c  s   | j s
dS d}|V  dt| V  t| jj| jdD ]}|V  dV  q6| j  D ](\}\}}|V  |rRtt|	 V  qRdV  dS )z4Yield the lines for the subcommand part of the help.NZSubcommandsr   )r0   r$   )
r   r   r   r[   rO   rW   r   r   r   r   )rP   r   r   subc_rs   r;   r;   r<   r   Z  s    z!Application.emit_subcommands_helpboolc                 c  s   |sdV  dV  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;   rP   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  |r||  }|rbdV  dV  t| jD ]}|V  dV  qP|D ]}| V  dV  qf|  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   rZ   Zclass_get_helpemit_examplesr   )rP   r^   Zhelp_classesr   r   r;   r;   r<   r   {  s     
zApplication.emit_helprH   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   re   r;   r;   r<   r     s     z6Application.document_config_options.<locals>.<genexpr>)r   rg   r   r;   r;   r<   document_config_options  s    z#Application.document_config_optionsc                 C  s   t d|   dS )z"Print the application description.r   N)r   r   r   r   r;   r;   r<   print_description  s    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   rX   rS   )rP   r   r;   r;   r<   r     s    zApplication.emit_descriptionc                 C  s   t d|   dS )z1Print usage and examples (see `emit_examples()`).r   N)r   r   r   r   r;   r;   r<   print_examples  s    zApplication.print_examplesc                 c  s6   | j r2dV  dV  dV  tt| j  V  dV  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   rh   r   r;   r;   r<   print_version  s    zApplication.print_version)r   r#   r-   c                 C  s   | j |}|dk	st|\}}t|tr2t|}t|tr`t|tr`| j	
  |j| d| _n t|rt|| | _ntd| | j| dS )z"Initialize a subcommand with argv.N)rf   z%Invalid mappings for subcommand '%s'!)r   getr   r   rH   r"   r   rb   r.   rR   Zclear_instanceinstancer   callabler   )rP   r   r#   r   r   r   r;   r;   r<   initialize_subcommand  s    

z!Application.initialize_subcommandz)tuple[dict[str, t.Any], dict[str, t.Any]]c                 C  sf  t t}| jD ]0}|j}| dd D ]}||j | q(qi }| j D ]r\}}t|t	rh|\}}|
dd\}}	|| }
t|
dkr|
d }t|t	s|f}|D ]}d||	g||< qqNi }| j D ]\}\}}i }| D ]H\}}|| }
t|
dkr|
d }||kr(|| | q|||< qt|t	sD|f}|D ]}||f||< qHq||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.

        r3   r   r|   r   )r   listr^   rD   ra   appendr   r   r   r   r   r   r   r   update)rP   Zmro_treer   clsnamerf   r   r   r   r   r   childrenalr   r   Zflagdictrs   ZnewflagZsubdictkr;   r;   r<   flatten_flags  s@    




zApplication.flatten_flagszlist[str] | Noner   )r#   r   r   r^   r-   c                 C  s   t ||||| j| jdS )N)r^   r4   r   )r   r4   r   )rP   r#   r   r   r^   r;   r;   r<   _create_loader  s         zApplication._create_loaderz	list[str])check_argcompleter-   c              	   C  sR   |rLdt jkrLz$ddlm} | }|dk	s.t|W S  ttfk
rJ   Y nX 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  r   ImportErrorModuleNotFoundErrorr   r#   )r   r  r  cwordsr;   r;   r<   _get_sys_argv  s    zApplication._get_sys_argvc              	   C  sB   dt jkrdS zddlm} |  W n ttfk
r<   Y nX dS )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t|dkr0| jt| jddd }dd |D | _|rb|d dkrb|dd dg }| jrt|dkr|d |dd  }}t	d	|r|| jkr| 
  | ||S z|d|d
  W n tk
r   | Y nX t fdddD r| d k | d d ks(d kr:|   | d |  \}}t|  }| j||||d}zt| | _W n tk
r    Y nX | | j |j| _dS )z!Parse the command line arguments.N)r  r3   c                 S  s   g | ]}t |qS r;   r    )r   argr;   r;   r<   
<listcomp>M  s     z2Application.parse_command_line.<locals>.<listcomp>r   rs   -hz^\w(\-?\w)*$r   c                 3  s   | ]}| kV  qd S r   r;   )r   xZinterpreted_argvr;   r<   r   d  s     z1Application.parse_command_line.<locals>.<genexpr>)r  
--help-allz--helpr   z	--versionz-Vr   )r   rH   r   r  r   r   r#   r   rematchr  r  index
ValueErroranyr   r8   r  r  r  r   r  r   load_config
cli_config
SystemExitupdate_config
extra_args)rP   r#   r   Zsubargvr   r   r^   loaderr;   r  r<   r   G  s<    


zApplication.parse_command_linez#str | t.Sequence[str | None] | NonezAnyLogger | Nonezt.Generator[t.Any, None, None])basefilenamepathr4   raise_config_file_errorsr-   c                 c  s^  t |ts|dkr|g}t|D ]6}| j|d ||d}|rT|d||pPt  | j|d ||d}g }g }	||fD ]}
d}z|
 }W nJ t	k
r   Y nJ t
k
r   |
jp|}|r |r|jd|dd Y nX |r|d	|
j |rxt|	|D ]:\}}||}|r|r|d
||
jtj|dd q||
jfV  || |	|
j qxq dS )zeLoad config files (py,json) by filename and path.

        yield each config object in turn.
        Nz.py)r-  r4   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   rH   r`   python_config_loader_classr6   r  getcwdjson_config_loader_classr&  r   r   Zfull_filenamer   zip
collisionswarningrO   r   dumpsr  )r   r,  r-  r4   r.  currentZpyloaderZ
jsonloaderZloaded	filenamesr+  r7   filenameZearlier_configr4  r;   r;   r<   _load_config_filesz  sJ    


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_files)r9  r-  r-   c                 C  sp   t j|\}}t }| j||| j| jdD ](\}}|| || jkr,| j	| q,|| j
 | | dS )z'Load config files by filename and path.)r-  r4   r.  N)r  r-  splitextr   r:  r4   r.  merger   r  r'  r)  )rP   r9  r-  extZ
new_configr7   fnamer;   r;   r<   load_config_file  s    
zApplication.load_config_filec                 #  s   |dkr| j }tdd | |D  ddd fdd  }tfd	d  D   |kr:qhq:  D ]\}}|rp|V  qpd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 )Trt   N)r   Zclass_own_traits)r   r   r;   r;   r<   r     s   z:Application._classes_with_config_traits.<locals>.<genexpr>r/   r   )r   r-   c                   s   t  fdd| jD S )Nc                 3  s   | ]}| k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>)r%  	__bases__)r   rB  r;   r<   is_any_parent_included  s    zGApplication._classes_with_config_traits.<locals>.is_any_parent_includedc                 3  s"   | ]\}}||p |fV  qd S r   r;   )r   r   inc_yes)rE  r;   r<   r     s   )r^   r   rg   r   r   )rP   r^   Zto_incl_origclrF  r;   )rC  rE  r<   r     s    z'Application._classes_with_config_traitsc                 C  sn   d| j  g}|d |d |d |dkr8| jn|}t| |}|D ]}||| qNd|S )z/generate default config file from Configurablesz# Configuration file for %s.r$   zc = get_config()  #noqaNr   )rW   r  r^   r  r   Zclass_config_sectionr   )rP   r^   linesZconfig_classesr   r;   r;   r<   generate_config_file  s    


z Application.generate_config_filec              
   C  s@   t | ddr<| jjD ] }tt |  W 5 Q R X qd| _d S )Nr   F)r   r4   r~   r   r   closer   )rP   handlerr;   r;   r<   close_handlers  s
    
zApplication.close_handlersr   zint | str | None)exit_statusr-   c                 C  s(   | j d| j  |   t| d S )NzExiting application: %s)r4   r6   rW   rL  r   r8   )rP   rM  r;   r;   r<   r8     s    zApplication.exitc                 C  s   |    d S r   )rL  r   r;   r;   r<   __del__  s    zApplication.__del__)r#   r2   r-   c                 K  s"   | j f |}|| |  dS )zLaunch a global instance of this Application

        If a global instance already exists, this reinitializes and starts it
        N)r  r   r   )r   r#   r2   r0   r;   r;   r<   launch_instance  s    
zApplication.launch_instance)N)N)F)F)N)F)N)NF)N)N)N)r   )N)brD   rE   rF   rS   r   rW   __annotations__rX   rY   rZ   r[   r   r0  r   r2  r\   r^   rg   rh   r   r#   r   r%   r.  r   rT   rU   tagr   rG   r   r   r   r   r   r   r   r   r   r   r   r   r   rn   r   r   r   r   r*  r   r'  r   r   r   r   r   r   r   r   rB   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   r:  propertyr;  r@  r   rI  rL  r8   rN  rO  rV   r;   r;   rQ   r<   r.      s&  
  3
07	 
 
  
	!&	;2  7  *
r.   rH   ru   )rW   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   )rW   rT  rU  rV  r   r   setterZunsetterr;   r;   r<   boolean_flag(  s    rX  r   rv   c                   C  s   t  rt  jS t S dS )z|Get the config object for the global Application instance, if there is one

    otherwise return an empty config object
    N)r.   Zinitializedr  r7   r   r;   r;   r;   r<   
get_configG  s    
rY  __main__)r$   r$   )brS   
__future__r   r>   r   rT   r  r   r!  r   typingr@   collectionsr   r   
contextlibr   r   r   logging.configr   textwrapr   Ztraitlets.config.configurabler	   r
   Ztraitlets.config.loaderr   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   rY   rZ   hasattrr#   r[   r  r  Z_envvarlowerr%   r$  
executableendswithr   TypeVarCallableAnyr*   UnionLoggerLoggerAdapterr   rH   ru   Optionalr   r   r]   rB   r   rC   	FormatterrG   r.   r   Zdefault_aliasesr   Zdefault_flagsrX  rY  rD   rO  r;   r;   r;   r<   <module>   sx    0
       
