3
Êb_‘Z  ã               @   s  U d Z ddlmZ ddlmZ ddlZddlmZmZm	Z	m
Z
 ddl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dd„ ZdJdd„Zdd„ ZdKdd„ZdLdd„Z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%ƒZ'dMee(d&œd'd(„a)dNd)d*„Z*d+d,„ Z+d-d.„ Z,d/d0„ Z-d1d2„ Z.d3d4„ Z/d5d6„ Z0d7d8„ Z1d9d:„ Z2dOd<d=„Z3ed>d?„ ƒZ4d@dA„ Z5dBdC„ Z6dDdE„ Z7dFdG„ Z8e5e9ƒZ:e5e;ƒZ<e5e=ƒZ>e5eƒZ?e6ee@fƒZAdHdI„ ZBdS )Paò  
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)ÚcontextmanagerN)ÚAnyÚDictÚIterableÚListÚDeprecatedOptionzkey msg rkey removal_verÚRegisteredOptionzkey defval doc validator cbÚallc               @   s   e Zd ZdZdS )ÚOptionErrorzPException for pandas.options, backwards compatible with KeyError
    checks
    N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r   r   ú7/tmp/pip-build-jkwsxyiy/pandas/pandas/_config/config.pyr   I   s   r   c             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)ÚpatÚsilentÚkeysÚkeyr   r   r   Ú_get_single_keyS   s    r   Fc             C   s   t | |ƒ}t|ƒ\}}|| S )N)r   Ú	_get_root)r   r   r   ÚrootÚkr   r   r   Ú_get_optione   s    
r    c        
   
   O   sô   t | ƒ}| s|d dkr"tdƒ‚|jddƒ}|rRt|jƒ ƒd }td|› d�ƒ‚xœt| d d d… | dd d… ƒD ]z\}}t||ƒ}t|ƒ}|r |j	r |j	|ƒ t
|ƒ\}	}||	|< |jrr|rât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_optionm   s&    (


r4   Ú Tc             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   Ú_print_descr   Úsr   r   r   Ú_describe_option�   s    
r>   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
   z’You 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$   r4   Ú_registered_optionsÚdefval)r   r   r   r   r   r   r   Ú_reset_option›   s     
rB   c             C   s   t | dd�}t|ƒjS )NT)r   )r   r)   rA   )r   r   r   r   r   Úget_default_val®   s    rC   c               @   s8   e Zd ZdZddd„Zdd„ Zedœdd	„Zd
d„ ZdS )ÚDictWrapperz0 provide attribute-style access to a nested dictr5   c             C   s    t j| d|ƒ t j| d|ƒ d S )NÚdÚprefix)ÚobjectÚ__setattr__)ÚselfrE   rF   r   r   r   Ú__init__¶   s    zDictWrapper.__init__c             C   sT   t j| dƒ}|r|d7 }||7 }|| jkrHt| j| tƒ rHt||ƒ ntdƒ‚d S )NrF   Ú.z.You can only set the value of existing options)rG   Ú__getattribute__rE   Ú
isinstanceÚdictr4   r   )rI   r   ÚvalrF   r   r   r   rH   º   s    zDictWrapper.__setattr__)r   c             C   sr   t j| dƒ}|r|d7 }||7 }yt j| dƒ| }W n tk
rP   tdƒ‚Y nX t|tƒrft||ƒS t|ƒS d S )NrF   rK   rE   zNo such option)rG   rL   ÚKeyErrorr   rM   rN   rD   r    )rI   r   rF   r2   r   r   r   Ú__getattr__Æ   s    

zDictWrapper.__getattr__c             C   s   t | jjƒ ƒS )N)r&   rE   r   )rI   r   r   r   Ú__dir__Ô   s    zDictWrapper.__dir__N)r5   )	r   r   r   r   rJ   rH   ÚstrrQ   rR   r   r   r   r   rD   ³   s
   
rD   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__)rI   ÚfuncZdoc_tmplr   r   r   rJ   â   s    zCallableDynamicDoc.__init__c             O   s   | j ||ŽS )N)rV   )rI   r.   Ú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)r>   Úpp_options_listr&   r@   r   rU   Úformat)rI   rZ   r[   r   r   r   r   é   s    zCallableDynamicDoc.__doc__N)r   r   r   rJ   rY   Úpropertyr   r   r   r   r   rT   á   s   rT   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&   r(   Úops)rI   r.   r   r   r   rJ   ‰  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    )r8   r   rO   r   r   r   r9   ’  s    z,option_context.__enter__.<locals>.<listcomp>T)r   )r`   Úundor4   )rI   r   rO   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   )ra   r4   )rI   r.   r   rO   r   r   r   Ú__exit__—  s    zoption_context.__exit__N)r   r   r   r   rJ   rb   rc   r   r   r   r   r_   |  s   r_   )r   rA   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 |ƒsŒt
|› d	�ƒ‚|j|ƒrdt
|› d
�ƒ‚qdW t}	d}
x^t|dd… ƒD ]J\}}t|	tƒsòt|
jdj|d|… ƒd�ƒ‚||	k�ri |	|< |	| }	qÂW 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       - a fully-qualified key, e.g. "x.y.option - z".
    defval    - the default value of the option
    doc       - a string description of the option
    validator - a 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.

    Returns
    -------
    Nothing.

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

    r   NzOption 'z' has already been registeredz' is a reserved keyrK   ú^ú$z is not a valid identifierz is a python keywordz5Path prefix to option '{option}' is already an optionr   )Úoption)r   rA   Údocr*   r+   éÿÿÿÿrh   rh   )ÚtokenizeÚkeywordÚlowerr@   r   Ú_reserved_keysÚsplitÚreÚmatchÚNamer$   Ú	iskeywordÚ_global_configÚ	enumeraterM   rN   r]   r:   r	   )r   rA   rg   r*   r+   ri   rj   Úpathr   ÚcursorÚmsgÚiÚpr   r   r   Úregister_option�  s8    




ry   c             C   s6   | j ƒ } | tkr td| › d�ƒ‚t| |||ƒt| < dS )a3  
    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 - the name of the option to be deprecated. must be a fully-qualified
          option name (e.g "x.y.z.rkey").

    msg - (Optional) a warning message to output when the key is referenced.
          if no message is given a default message will be emitted.

    rkey - (Optional) the 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.

    Returns
    -------
    Nothing

    Raises
    ------
    OptionError - if key has already been deprecated.

    zOption 'z)' has already been defined as deprecated.N)rk   Ú_deprecated_optionsr   r   )r   rv   ÚrkeyÚremoval_verr   r   r   Údeprecate_optionâ  s    'r}   c                s8   ˆ t krˆ gS tt jƒ ƒ}ˆ dkr&|S ‡ fdd„|D ƒS )z]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   )rn   ÚsearchÚI)r8   r   )r   r   r   r9   $  s    z#_select_options.<locals>.<listcomp>)r@   Úsortedr   )r   r   r   )r   r   r     s    r   c             C   s8   | j dƒ}t}x|d d… D ]}|| }qW ||d fS )NrK   r   rh   rh   )rm   rr   )r   rt   ru   rx   r   r   r   r   '  s
    
r   c             C   s   | j ƒ } | tkS )z6 Returns True if the given option has been deprecated )rk   rz   )r   r   r   r   Ú_is_deprecated/  s    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)rz   rP   )r   rE   r   r   r   Ú_get_deprecated_option6  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
    )r@   Úget)r   r   r   r   r)   G  s    r)   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   rE   r   r   r   r   R  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‚   rv   r;   r,   ÚwarnÚFutureWarningr|   r{   )r   rE   rv   r   r   r   r   _  s    	
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 ú r6   zNo description available.z
    [default: z] [currently: Tú]r5   z
    (Deprecatedz, use `z
` instead.ú))	r)   r‚   rg   r:   Ústriprm   rA   r    r{   )r   r3   rE   r=   r{   r   r   r   r7   {  s    
r7   éP   c       
         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 }q‚W dj	|ƒ}	|rÊt
|	ƒ n|	S dS )zB Builds a concise listing of available options, grouped by prefix r   )Úwrap)Úgroupby)ÚnameÚksÚreturnc                sP   | rd|  d nd}ˆdj |ƒˆ |ddd�}|rL|d
 rL| rL|d d	 |d< |S )Nz- z.[r5   z, z  F)Úinitial_indentÚsubsequent_indentÚbreak_long_wordsr   rˆ   rh   rh   rh   )r:   )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 )rK   r   )Úfind)r8   Úxr   r   r   r9   ¨  s    z#pp_options_list.<locals>.<listcomp>r5   c             S   s   g | ]}|j d ƒdkr|‘qS )rK   r   )r˜   )r8   r™   r   r   r   r9   «  s    c             S   s   | d | j dƒ… S )NrK   )Úrfind)r™   r   r   r   Ú<lambda>­  s    z!pp_options_list.<locals>.<lambda>c                s    g | ]}|t ˆ ƒd  d… ‘qS )r   N)r   )r8   r™   )r   r   r   r9   ®  s    r6   N)ÚtextwraprŒ   Ú	itertoolsr�   rS   r   r   r€   r&   r:   r;   )
r   r–   Z_printr�   r—   r•   ZsinglesÚgr�   r=   r   )r   r–   rŒ   r   r\   ”  s     

r\   c             #   sF   ‡ 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.
    c                s   ‡ ‡fdd„}|S )Nc                s   ˆ› d| › �}ˆ |f|ž|ŽS )NrK   r   )r   r.   rX   Zpkey)rW   rF   r   r   ÚinnerÚ  s    z*config_prefix.<locals>.wrap.<locals>.innerr   )rW   rŸ   )rF   )rW   r   rŒ   Ù  s    zconfig_prefix.<locals>.wrapN)ry   Ú
get_optionÚ
set_option)rF   rŒ   Z_register_optionr    r4   r   )rF   r   Úconfig_prefix»  s    r¢   c                s   ‡ 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`

    c                s    t | ƒˆ krtdˆ › d�ƒ‚d S )NzValue must have type 'r„   )Útyper$   )r™   )Ú_typer   r   rŸ   þ  s    zis_type_factory.<locals>.innerr   )r¤   rŸ   r   )r¤   r   Úis_type_factoryð  s    r¥   c                sF   t ˆ ttfƒr(tˆ ƒ‰ djttˆ ƒƒ‰n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„   c                s   t | ˆ ƒstdˆ› �ƒ‚d S )NzValue must be an instance of )rM   r$   )r™   )r¤   Ú	type_reprr   r   rŸ     s    
z"is_instance_factory.<locals>.inner)rM   Útupler&   r:   ÚmaprS   )r¤   rŸ   r   )r¤   r§   r   Úis_instance_factory  s    rª   c                s.   dd„ ˆD ƒ‰ dd„ ˆD ƒ‰‡ ‡fdd„}|S )Nc             S   s   g | ]}t |ƒr|‘qS r   )Úcallable)r8   Úcr   r   r   r9   "  s    z%is_one_of_factory.<locals>.<listcomp>c             S   s   g | ]}t |ƒs|‘qS r   )r«   )r8   r¬   r   r   r   r9   #  s    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   )r8   r¬   )r™   r   r   ú	<genexpr>(  s    z3is_one_of_factory.<locals>.inner.<locals>.<genexpr>c             S   s   g | ]}t |ƒ‘qS r   )rS   )r8   Zlvalr   r   r   r9   )  s    z4is_one_of_factory.<locals>.inner.<locals>.<listcomp>r¦   zValue must be one of z or a callable)Úanyr:   r   r$   )r™   ZuvalsZ	pp_valuesrv   )Ú	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±   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)rM   Úintr$   )Úvaluerv   r   r   r   Úis_nonnegative_int3  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_callableV  s    r¶   )F)r5   T)F)r5   NN)NNN)r‹   F)Cr   Úcollectionsr   Ú
contextlibr   rn   Útypingr   r   r   r   r,   r   r	   rz   rS   r@   rr   rl   ÚAttributeErrorrP   r   r   r    r4   r>   rB   rC   rD   rT   Z_get_option_tmplZ_set_option_tmplZ_describe_option_tmplZ_reset_option_tmplr    r¡   Zreset_optionZdescribe_optionÚoptionsr_   rG   ry   r}   r   r   r�   r‚   r)   r   r   r7   r\   r¢   r¥   rª   r±   r´   r²   Zis_intÚboolZis_boolÚfloatZis_floatZis_strÚbytesZis_textr¶   r   r   r   r   Ú<module>1   sh   



 

.-" 



!E
3
'5