3
pd#]              	   @   sF  U d Z ddlmZ ddlmZmZ ddlZddlmZm	Z	m
Z
mZmZmZmZmZmZ ddlZddlmZ eddZed	d
Zi Ze
eef i Ze
eef i Ze
eef dgZee G dd deeZeeedddZdXeedddZ ddddZ!dYeedddZ"dZeeddddZ#edd d!Z$G d"d# d#Z%G d$d% d%Z&d&Z'd'Z(d(Z)d)Z*e&e e'a+e&e!e(a,e&e#e*a-e&e"e)Z.e%eZ/G d*d+ d+eZ0d[ee1eee	egef  ee	egef  dd,d-d.a2d\eee ee dd/d0d1Z3eee d2d3d4Z4eee
eef ef d5d6d7Z5eed5d8d9Z6ed:d;d<Z7ed:d=d>Z8eed5d?d@Z9eed5dAdBZ:eedCdDdEZ;d]ee edGdHdIZ<edJdK Z=ee e	egdf dLdMdNZ>e	egdf ddOdPZ?e	egdf ddQdRZ@eeA ddSdTdUZBe>eAZCe>eZDe>eEZFe>eZGe?eeHfZIeddVdWZJdS )^a  
The config module holds package-wide configurables and provides
a uniform API for working with them.

Overview
========

This module supports the following requirements:
- options are referenced using keys in dot.notation, e.g. "x.y.option - z".
- keys are case-insensitive.
- functions should accept partial/regex keys, when unambiguous.
- options can be registered by modules at import time.
- options can be registered at init-time (via core.config_init)
- options have a default value, and (optionally) a description and
  validation function associated with them.
- options can be deprecated, in which case referencing them
  should produce a warning.
- deprecated options can optionally be rerouted to a replacement
  so that accessing a deprecated option reroutes to a differently
  named option.
- options can be reset to their default value.
- all option can be reset to their default value at once.
- all options in a certain sub - namespace can be reset at once.
- the user can set / get / reset or ask for the description of an option.
- a developer can register and mark an option as deprecated.
- you can register a callback to be invoked when the option value
  is set or reset. Changing the stored value is considered misuse, but
  is not verboten.

Implementation
==============

- Data is stored using nested dictionaries, and should be accessed
  through the provided API.

- "Registered options" and "Deprecated options" have metadata associated
  with them, which are stored in auxiliary dictionaries keyed on the
  fully-qualified key, e.g. "x.y.z.option".

- the config_init module is imported by the package's __init__.py file.
  placing any register_option() calls there will ensure those options
  are available as soon as pandas is loaded. If you use register_option
  in a module, it will only be available after that module is imported,
  which you should be aware of.

- `config_prefix` is a context_manager (for use with the `with` keyword)
  which can save developers some typing, see the docstring.

    )
namedtuple)ContextDecoratorcontextmanagerN)	AnyCallableDictIterableListOptionalTupleTypecast)FDeprecatedOptionzkey msg rkey removal_verRegisteredOptionzkey defval doc validator cballc               @   s   e Zd ZdZdS )OptionErrorzU
    Exception for pandas.options, backwards compatible with KeyError
    checks
    N)__name__
__module____qualname____doc__ r   r   7/tmp/pip-build-7vycvbft/pandas/pandas/_config/config.pyr   K   s   r   )patsilentreturnc             C   sf   t | }t|dkr2|s t|  tdt|  t|dkrFtd|d }|sZt| t|}|S )Nr   zNo such keys(s):    zPattern matched multiple keys)_select_optionslen_warn_if_deprecatedr   repr_translate_key)r   r   keyskeyr   r   r   _get_single_keyV   s    r$   F)r   r   c             C   s   t | |}t|\}}|| S )N)r$   	_get_root)r   r   r#   rootkr   r   r   _get_optionh   s    
r(   )r   c        
   
   O   s   t | }| s|d dkr"td|jdd}|rRt|j d }td| dxt| d d d | dd d D ]z\}}t||}t|}|r|j	r|j	| t
|\}	}||	|< |jrr|rtjd	d
 |j| W d Q R X qr|j| qrW d S )N   r   z4Must provide an even number of non-keyword argumentsr   Fz2_set_option() got an unexpected keyword argument ""r   T)record)r   
ValueErrorpoplistr"   	TypeErrorzipr$   _get_registered_option	validatorr%   cbwarningscatch_warnings)
argskwargsnargsr   kwargr'   vr#   or&   r   r   r   _set_optionp   s&    (


r<    T)r   _print_descc             C   sF   t | }t|dkrtddjdd |D }|r>t| n|S d S )Nr   zNo such keys(s)
c             S   s   g | ]}t |qS r   )_build_option_description).0r'   r   r   r   
<listcomp>   s    z$_describe_option.<locals>.<listcomp>)r   r   r   joinprint)r   r>   r"   sr   r   r   _describe_option   s    
rF   c             C   sj   t | }t|dkrtdt|dkrDt| dk rD| dkrDtdx |D ]}t|t| j|d qJW d S )Nr   zNo such keys(s)r      r   zYou must specify at least 4 characters when resetting multiple keys, use the special keyword "all" to reset all the options to their default value)r   )r   r   r   r,   r<   _registered_optionsdefval)r   r   r"   r'   r   r   r   _reset_option   s     
rJ   )r   c             C   s   t | dd}t|jS )NT)r   )r$   r1   rI   )r   r#   r   r   r   get_default_val   s    rK   c               @   s\   e Zd ZdZdeeef edddZeedddd	Zed
ddZ	e
e dddZdS )DictWrapperz0 provide attribute-style access to a nested dictr=   )dprefixc             C   s    t j| d| t j| d| d S )NrM   rN   )object__setattr__)selfrM   rN   r   r   r   __init__   s    zDictWrapper.__init__N)r#   valr   c             C   sT   t j| d}|r|d7 }||7 }|| jkrHt| j| t rHt|| ntdd S )NrN   .z.You can only set the value of existing options)rO   __getattribute__rM   
isinstancedictr<   r   )rQ   r#   rS   rN   r   r   r   rP      s    zDictWrapper.__setattr__)r#   c             C   s   t j| d}|r|d7 }||7 }yt j| d| }W n, tk
r` } ztd|W Y d d }~X nX t|trvt||S t|S d S )NrN   rT   rM   zNo such option)rO   rU   KeyErrorr   rV   rW   rL   r(   )rQ   r#   rN   r:   errr   r   r   __getattr__   s    

zDictWrapper.__getattr__)r   c             C   s   t | jj S )N)r.   rM   r"   )rQ   r   r   r   __dir__   s    zDictWrapper.__dir__)r=   )r   r   r   r   r   strr   rR   rP   rZ   r   r[   r   r   r   r   rL      s
   rL   c               @   s(   e Zd Zdd Zdd Zedd ZdS )CallableDynamicDocc             C   s   || _ || _d S )N)__doc_tmpl____func__)rQ   funcZdoc_tmplr   r   r   rR      s    zCallableDynamicDoc.__init__c             O   s   | j ||S )N)r_   )rQ   r6   kwdsr   r   r   __call__   s    zCallableDynamicDoc.__call__c             C   s,   t ddd}tttj }| jj||dS )Nr   F)r>   )	opts_desc	opts_list)rF   pp_options_listr.   rH   r"   r^   format)rQ   rc   rd   r   r   r   r      s    zCallableDynamicDoc.__doc__N)r   r   r   rR   rb   propertyr   r   r   r   r   r]      s   r]   a;  
get_option(pat)

Retrieves the value of the specified option.

Available options:

{opts_list}

Parameters
----------
pat : str
    Regexp which should match a single option.
    Note: partial matches are supported for convenience, but unless you use the
    full option name (e.g. x.y.z.option_name), your code may break in future
    versions if new options with similar names are introduced.

Returns
-------
result : the value of the option

Raises
------
OptionError : if no such option exists

Notes
-----
The available options with its descriptions:

{opts_desc}
aG  
set_option(pat, value)

Sets the value of the specified option.

Available options:

{opts_list}

Parameters
----------
pat : str
    Regexp which should match a single option.
    Note: partial matches are supported for convenience, but unless you use the
    full option name (e.g. x.y.z.option_name), your code may break in future
    versions if new options with similar names are introduced.
value : object
    New value of option.

Returns
-------
None

Raises
------
OptionError if no such option exists

Notes
-----
The available options with its descriptions:

{opts_desc}
a  
describe_option(pat, _print_desc=False)

Prints the description for one or more registered options.

Call with not arguments to get a listing for all registered options.

Available options:

{opts_list}

Parameters
----------
pat : str
    Regexp pattern. All matching keys will have their description displayed.
_print_desc : bool, default True
    If True (default) the description(s) will be printed to stdout.
    Otherwise, the description(s) will be returned as a unicode string
    (for testing).

Returns
-------
None by default, the description(s) as a unicode string if _print_desc
is False

Notes
-----
The available options with its descriptions:

{opts_desc}
a5  
reset_option(pat)

Reset one or more options to their default value.

Pass "all" as argument to reset all options.

Available options:

{opts_list}

Parameters
----------
pat : str/regex
    If specified only options matching `prefix*` will be reset.
    Note: partial matches are supported for convenience, but unless you
    use the full option name (e.g. x.y.z.option_name), your code may break
    in future versions if new options with similar names are introduced.

Returns
-------
None

Notes
-----
The available options with its descriptions:

{opts_desc}
c               @   s(   e Zd ZdZdd Zdd Zdd ZdS )	option_contexta  
    Context manager to temporarily set options in the `with` statement context.

    You need to invoke as ``option_context(pat, val, [(pat, val), ...])``.

    Examples
    --------
    >>> with option_context('display.max_rows', 10, 'display.max_columns', 5):
    ...     ...
    c             G   sL   t |d dkot |dks$tdtt|d d d |dd d | _d S )Nr)   r   z>Need to invoke as option_context(pat, val, [(pat, val), ...]).r   )r   r,   r.   r0   ops)rQ   r6   r   r   r   rR     s    zoption_context.__init__c             C   s8   dd | j D | _x | j D ]\}}t||dd qW d S )Nc             S   s    g | ]\}}|t |d dfqS )T)r   )r(   )rA   r   rS   r   r   r   rB     s    z,option_context.__enter__.<locals>.<listcomp>T)r   )ri   undor<   )rQ   r   rS   r   r   r   	__enter__  s    zoption_context.__enter__c             G   s,   | j r(x | j D ]\}}t||dd qW d S )NT)r   )rj   r<   )rQ   r6   r   rS   r   r   r   __exit__  s    zoption_context.__exit__N)r   r   r   r   rR   rk   rl   r   r   r   r   rh   ~  s   
rh   )r#   rI   docr2   r3   r   c             C   s`  ddl }ddl}| j } | tkr0td|  d| tkrHtd|  d|rT|| | jd}xH|D ]@}tjd|j	 d |st
| d	|j|rdt
| d
qdW t}	d}
x^t|dd D ]J\}}t|	tst|
jdj|d| d||	kri |	|< |	| }	qW t|	ts:t|
jdj|dd d||	|d < t| ||||dt| < dS )a  
    Register an option in the package-wide pandas config object

    Parameters
    ----------
    key : str
        Fully-qualified key, e.g. "x.y.option - z".
    defval : object
        Default value of the option.
    doc : str
        Description of the option.
    validator : Callable, optional
        Function of a single argument, should raise `ValueError` if
        called with a value which is not a legal value for the option.
    cb
        a function of a single argument "key", which is called
        immediately after an option value is set/reset. key is
        the full name of the option.

    Raises
    ------
    ValueError if `validator` is specified and `defval` is not a valid value.

    r   NzOption 'z' has already been registeredz' is a reserved keyrT   ^$z is not a valid identifierz is a python keywordz5Path prefix to option '{option}' is already an optionr   )option)r#   rI   rm   r2   r3   rq   rq   )keywordtokenizelowerrH   r   _reserved_keyssplitrematchNamer,   	iskeyword_global_config	enumeraterV   rW   rf   rC   r   )r#   rI   rm   r2   r3   rr   rs   pathr'   cursormsgipr   r   r   register_option  s8    




r   )r#   r   rkeyr   c             C   s6   | j  } | tkr td|  dt| |||t| < dS )a  
    Mark option `key` as deprecated, if code attempts to access this option,
    a warning will be produced, using `msg` if given, or a default message
    if not.
    if `rkey` is given, any access to the key will be re-routed to `rkey`.

    Neither the existence of `key` nor that if `rkey` is checked. If they
    do not exist, any subsequence access will fail as usual, after the
    deprecation warning is given.

    Parameters
    ----------
    key : str
        Name of the option to be deprecated.
        must be a fully-qualified option name (e.g "x.y.z.rkey").
    msg : str, optional
        Warning message to output when the key is referenced.
        if no message is given a default message will be emitted.
    rkey : str, optional
        Name of an option to reroute access to.
        If specified, any referenced `key` will be
        re-routed to `rkey` including set/get/reset.
        rkey must be a fully-qualified option name (e.g "x.y.z.rkey").
        used by the default message if no `msg` is specified.
    removal_ver : optional
        Specifies the version in which this option will
        be removed. used by the default message if no `msg` is specified.

    Raises
    ------
    OptionError
        If the specified key has already been deprecated.
    zOption 'z)' has already been defined as deprecated.N)rt   _deprecated_optionsr   r   )r#   r   r   removal_verr   r   r   deprecate_option  s    $r   )r   r   c                s8    t kr gS tt j } dkr&|S  fdd|D S )zb
    returns a list of keys matching `pat`

    if pat=="all", returns all registered options
    r   c                s    g | ]}t j |t jr|qS r   )rw   searchI)rA   r'   )r   r   r   rB   *  s    z#_select_options.<locals>.<listcomp>)rH   sortedr"   )r   r"   r   )r   r   r     s    r   )r#   r   c             C   s8   | j d}t}x|d d D ]}|| }qW ||d fS )NrT   r   rq   rq   )rv   r{   )r#   r}   r~   r   r   r   r   r%   -  s
    
r%   c             C   s   | j  } | tkS )z6 Returns True if the given option has been deprecated )rt   r   )r#   r   r   r   _is_deprecated5  s    r   )r#   c             C   s*   yt |  }W n tk
r    dS X |S dS )z
    Retrieves the metadata for a deprecated option, if `key` is deprecated.

    Returns
    -------
    DeprecatedOption (namedtuple) if key is deprecated, None otherwise
    N)r   rX   )r#   rM   r   r   r   _get_deprecated_option;  s
    r   c             C   s
   t j| S )z
    Retrieves the option metadata if `key` is a registered option.

    Returns
    -------
    RegisteredOption (namedtuple) if key is deprecated, None otherwise
    )rH   get)r#   r   r   r   r1   K  s    r1   c             C   s   t | }|r|jp| S | S dS )z
    if key id deprecated and a replacement key defined, will return the
    replacement key, otherwise returns `key` as - is
    N)r   r   )r#   rM   r   r   r   r!   V  s    
r!   c             C   s   t | }|r|jr,t|j tj|jt nPd|  d}|jrN|d|j 7 }|jrh|d|j d7 }n|d7 }tj|t dS dS )	z
    Checks if `key` is a deprecated option and if so, prints a warning.

    Returns
    -------
    bool - True if `key` is deprecated, False otherwise.
    'z' is deprecatedz and will be removed in z, please use 'z
' instead.z, please refrain from using it.TF)r   r   rD   r4   warnFutureWarningr   r   )r#   rM   r   r   r   r   r   b  s    
r   )r'   r   c             C   s   t | }t| }|  d}|jr<|dj|jj jd7 }n|d7 }|rf|d|j dt| d d7 }|r|jrv|jnd}|d	7 }|d
| d7 }|d7 }|S )zE Builds a formatted description of a registered option and prints it  r?   zNo description available.z
    [default: z] [currently: T]r=   z
    (Deprecatedz, use `z
` instead.))	r1   r   rm   rC   striprv   rI   r(   r   )r'   r;   rM   rE   r   r   r   r   r@   }  s    
r@   P   )r"   _printc       
         s   ddl m} ddlm ttt tt dfdd}g }dd t| D }|r`||d	|7 }d
d | D } xB|t| dd D ],\ } fddt|D }|| |7 }qW dj	|}	|rt
|	 n|	S dS )zB Builds a concise listing of available options, grouped by prefix r   )groupby)wrap)nameksr   c                sP   | rd|  d nd}dj | |ddd}|rL|d
 rL| rL|d d	 |d< |S )Nz- z.[r=   z, z  F)initial_indentsubsequent_indentbreak_long_wordsr   r   rq   rq   rq   )rC   )r   r   pfxls)widthr   r   r   pp  s    zpp_options_list.<locals>.ppc             S   s   g | ]}|j d dk r|qS )rT   r   )find)rA   xr   r   r   rB     s    z#pp_options_list.<locals>.<listcomp>r=   c             S   s   g | ]}|j d dkr|qS )rT   r   )r   )rA   r   r   r   r   rB     s    c             S   s   | d | j d S )NrT   )rfind)r   r   r   r   <lambda>  s    z!pp_options_list.<locals>.<lambda>c                s    g | ]}|t  d  d qS )r   N)r   )rA   r   )r'   r   r   rB     s    r?   N)	itertoolsr   textwrapr   r\   r   r	   r   r.   rC   rD   )
r"   r   r   r   r   r   Zsinglesgr   rE   r   )r'   r   r   r   re     s     

re   c             #   sN   t t d fdd}t}t}t}|ta|ta|tadV  |a|a|adS )a  
    contextmanager for multiple invocations of API with a common prefix

    supported API functions: (register / get / set )__option

    Warning: This is not thread - safe, and won't work properly if you import
    the API functions into your module using the "from x import y" construct.

    Example
    -------
    import pandas._config.config as cf
    with cf.config_prefix("display.font"):
        cf.register_option("color", "red")
        cf.register_option("size", " 5 pt")
        cf.set_option(size, " 6 pt")
        cf.get_option(size)
        ...

        etc'

    will register options "display.font.color", "display.font.size", set the
    value of "display.font.size"... and so on.
    )r`   r   c                s   t d fdd}tt|S )N)r#   c                s    d|  } |f||S )NrT   r   )r#   r6   ra   Zpkey)r`   rN   r   r   inner  s    z*config_prefix.<locals>.wrap.<locals>.inner)r\   r   r   )r`   r   )rN   )r`   r   r     s    zconfig_prefix.<locals>.wrapN)r   r   
get_option
set_option)rN   r   Z_register_optionr(   r<   r   )rN   r   config_prefix  s    r   )_typer   c                s   dd fdd}|S )a  

    Parameters
    ----------
    `_type` - a type to be compared against (e.g. type(x) == `_type`)

    Returns
    -------
    validator - a function of a single argument x , which raises
                ValueError if type(x) is not equal to `_type`

    N)r   c                s    t |  krtd  dd S )NzValue must have type 'r   )typer,   )r   )r   r   r   r     s    zis_type_factory.<locals>.innerr   )r   r   r   )r   r   is_type_factory  s    r   c                sL   t  ttfr(t  djtt nd  ddd fdd}|S )z

    Parameters
    ----------
    `_type` - the type to be checked against

    Returns
    -------
    validator - a function of a single argument x , which raises
                ValueError if x is not an instance of `_type`

    |r   N)r   c                s   t |  std d S )NzValue must be an instance of )rV   r,   )r   )r   	type_reprr   r   r     s    
z"is_instance_factory.<locals>.inner)rV   tupler.   rC   mapr\   )r   r   r   )r   r   r   is_instance_factory  s    r   c                s4   dd D  dd D d d fdd}|S )Nc             S   s   g | ]}t |r|qS r   )callable)rA   cr   r   r   rB   !  s    z%is_one_of_factory.<locals>.<listcomp>c             S   s   g | ]}t |s|qS r   )r   )rA   r   r   r   r   rB   "  s    )r   c                s\    krXt  fddD sXdd D }dj|}d| }trP|d7 }t|d S )Nc             3   s   | ]}| V  qd S )Nr   )rA   r   )r   r   r   	<genexpr>'  s    z3is_one_of_factory.<locals>.inner.<locals>.<genexpr>c             S   s   g | ]}t |qS r   )r\   )rA   Zlvalr   r   r   rB   (  s    z4is_one_of_factory.<locals>.inner.<locals>.<listcomp>r   zValue must be one of z or a callable)anyrC   r   r,   )r   ZuvalsZ	pp_valuesr   )	callableslegal_values)r   r   r   $  s    

z is_one_of_factory.<locals>.innerr   )r   r   r   )r   r   r   is_one_of_factory  s    r   )valuer   c             C   s2   | dkrdS t | tr"| dkr"dS d}t|dS )z
    Verify that value is None or a positive int.

    Parameters
    ----------
    value : None or int
            The `value` to be checked.

    Raises
    ------
    ValueError
        When the value is not None or is a negative integer
    Nr   z+Value must be a nonnegative integer or None)rV   intr,   )r   r   r   r   r   is_nonnegative_int2  s    
r   c             C   s   t | stddS )z

    Parameters
    ----------
    `obj` - the object to be checked

    Returns
    -------
    validator - returns True if object is callable
        raises ValueError otherwise.

    zValue must be a callableT)r   r,   )objr   r   r   is_callableT  s    r   )F)r=   T)F)r=   NN)NNN)r   F)Kr   collectionsr   
contextlibr   r   rw   typingr   r   r   r   r	   r
   r   r   r   r4   Zpandas._typingr   r   r   r   r\   rH   r{   ru   AttributeErrorrX   r   boolr$   r(   r<   rF   rJ   rK   rL   r]   Z_get_option_tmplZ_set_option_tmplZ_describe_option_tmplZ_reset_option_tmplr   r   Zreset_optionZdescribe_optionoptionsrh   rO   r   r   r   r%   r   r   r1   r!   r   r@   re   r   r   r   r   r   r   Zis_intZis_boolfloatZis_floatZis_strbytesZis_textr   r   r   r   r   <module>1   sr   ,

 .-" 



#  (H. &5