B @`\ @sVUdZddlmZddlmZmZddlZddlmZm Z m Z m Z m Z m Z mZmZmZddlZddlmZeddZed d ZiZe eefed <iZe eefed <iZe eefed <dgZe eed<GdddeeZeeedddZ d\eedddZ!ddddZ"d]eeddd Z#d^eeddd!d"Z$ed#d$d%Z%Gd&d'd'Z&Gd(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&eZ0Gd.d/d/eZ1d_ee2ee e egefe e egefdd0d1d2a3d`ee ee edd3d4d5Z4ee ed6d7d8Z5eee eefefd9d:d;Z6eed9dd?d@Z8ed>dAdBZ9eed9dCdDZ:eed9dEdFZ;eedGdHdIZeee egdfdPdQdRZ?e egdfddSdTZ@e egdfddUdVZAe eBddWdXdYZCe?eBZDe?eZEe?eFZGe?eZHe@eeIfZJeddZd[ZKdS)ba 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)ContextDecoratorcontextmanagerN) AnyCallableDictIterableListOptionalTupleTypecast)FDeprecatedOptionzkey msg rkey removal_verRegisteredOptionzkey defval doc validator cb_deprecated_options_registered_options_global_configall_reserved_keysc@seZdZdZdS) OptionErrorzU Exception for pandas.options, backwards compatible with KeyError checks N)__name__ __module__ __qualname____doc__rr9/tmp/pip-unpacked-wheel-q9tj5l6a/pandas/_config/config.pyrKsr)patsilentreturncCsft|}t|dkr2|s t|tdt|t|dkrFtd|d}|sZt|t|}|S)NrzNo such keys(s): zPattern matched multiple keys)_select_optionslen_warn_if_deprecatedrrepr_translate_key)rrkeyskeyrrr_get_single_keyVs  r(F)rrcCst||}t|\}}||S)N)r( _get_root)rrr'rootkrrr _get_optionhs  r,)rc Ost|}|r|ddkr td|dd}|rPt|d}td|dxt|ddd|dddD]z\}}t||}t|}|r|j r| |t |\} }|| |<|j rp|rt j d d | |WdQRXqp| |qpWdS) Nrz4Must provide an even number of non-keyword argumentsrFz2_set_option() got an unexpected keyword argument ""r T)record)r" ValueErrorpoplistr& TypeErrorzipr(_get_registered_option validatorr)cbwarningscatch_warnings) argskwargsnargsrkwargr+vr'or*rrr _set_optionps& (    r@T)r _print_desccCsFt|}t|dkrtdddd|D}|r>t|n|SdS)NrzNo such keys(s) cSsg|] }t|qSr)_build_option_description).0r+rrr sz$_describe_option..)r!r"rjoinprint)rrBr&srrr_describe_options  rJcCsjt|}t|dkrtdt|dkrDt|dkrD|dkrDtdx |D]}t|t|j|dqJWdS)NrzNo such keys(s)r rzYou 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"rr0r@rdefval)rrr&r+rrr _reset_options   rM)rcCst|dd}t|jS)NT)r)r(r5rL)rr'rrrget_default_vals rNc@s\eZdZdZdeeefedddZeedddd Zed d d Z e ed ddZ dS) DictWrapperz0 provide attribute-style access to a nested dictrA)dprefixcCs t|d|t|d|dS)NrPrQ)object __setattr__)selfrPrQrrr__init__szDictWrapper.__init__N)r'valrcCsRt|d}|r|d7}||7}||jkrFt|j|tsFt||ntddS)NrQ.z.You can only set the value of existing options)rR__getattribute__rP isinstancedictr@r)rTr'rVrQrrrrSs  zDictWrapper.__setattr__)r'c Cst|d}|r|d7}||7}yt|d|}Wn,tk r`}ztd|Wdd}~XYnXt|trvt||St|SdS)NrQrWrPzNo such option)rRrXKeyErrorrrYrZrOr,)rTr'rQr>errrrr __getattr__s   zDictWrapper.__getattr__)rcCst|jS)N)r2rPr&)rTrrr__dir__szDictWrapper.__dir__)rA) rrrrrstrrrUrSr]rr^rrrrrOs  rOc@s(eZdZddZddZeddZdS)CallableDynamicDoccCs||_||_dS)N) __doc_tmpl____func__)rTfuncZdoc_tmplrrrrUszCallableDynamicDoc.__init__cOs |j||S)N)rb)rTr:kwdsrrr__call__szCallableDynamicDoc.__call__cCs,tddd}ttt}|jj||dS)NrF)rB) opts_desc opts_list)rJpp_options_listr2rr&raformat)rTrfrgrrrrs zCallableDynamicDoc.__doc__N)rrrrUrepropertyrrrrrr`sr`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(eZdZdZddZddZddZdS) 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): ... ... cGsLt|ddkst|dkr$tdtt|ddd|ddd|_dS)Nr-rz>Need to invoke as option_context(pat, val, [(pat, val), ...]).r )r"r0r2r4ops)rTr:rrrrUszoption_context.__init__cCs8dd|jD|_x |jD]\}}t||ddqWdS)NcSs g|]\}}|t|ddfqS)T)r)r,)rErrVrrrrFsz,option_context.__enter__..T)r)rlundor@)rTrrVrrr __enter__szoption_context.__enter__cGs,|jr(x |jD]\}}t||ddqWdS)NT)r)rmr@)rTr:rrVrrr__exit__szoption_context.__exit__N)rrrrrUrnrorrrrrk~s rk)r'rLdocr6r7rc Cs`ddl}ddl}|}|tkr0td|d|tkrHtd|d|rT|||d}xH|D]@}td|j d|st |d | |rdt |d qdWt } d } x^t |dd D]J\} } t| tst| jd|d| d | | kri| | <| | } qWt| ts:t| jd|dd d || |d <t|||||dt|<dS)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. rNzOption 'z' has already been registeredz' is a reserved keyrW^$z is not a valid identifierz is a python keywordz5Path prefix to option '{option}' is already an option)option)r'rLrpr6r7)keywordtokenizelowerrrrsplitrematchNamer0 iskeywordr enumeraterYrZrirGr) r'rLrpr6r7rurvpathr+cursormsgiprrrregister_options8        r)r'rrkeyrcCs6|}|tkr td|dt||||t|<dS)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. zOption 'z)' has already been defined as deprecated.N)rwrrr)r'rr removal_verrrrdeprecate_options$r)rrcs8tkrgStt}dkr&|Sfdd|DS)zb returns a list of keys matching `pat` if pat=="all", returns all registered options rcs g|]}t|tjr|qSr)rysearchI)rEr+)rrrrF(sz#_select_options..)rsortedr&)rr&r)rrr!s  r!)r'rcCs8|d}t}x|ddD] }||}qW||dfS)NrWrs)rxr)r'r~rrrrrr)+s   r)cCs|}|tkS)z6 Returns True if the given option has been deprecated )rwr)r'rrr_is_deprecated3sr)r'cCs*y t|}Wntk r dSX|SdS)z Retrieves the metadata for a deprecated option, if `key` is deprecated. Returns ------- DeprecatedOption (namedtuple) if key is deprecated, None otherwise N)rr[)r'rPrrr_get_deprecated_option9s  rcCs t|S)z Retrieves the option metadata if `key` is a registered option. Returns ------- RegisteredOption (namedtuple) if key is deprecated, None otherwise )rget)r'rrrr5Isr5cCst|}|r|jp|S|SdS)z if key id deprecated and a replacement key defined, will return the replacement key, otherwise returns `key` as - is N)rr)r'rPrrrr%Ts r%cCst|}|r|jr,t|jt|jtnPd|d}|jrN|d|j7}|jrh|d|jd7}n|d7}t|tdSdS) 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)rrrHr8warn FutureWarningrr)r'rPrrrrr#`s   r#)r+rcCst|}t|}|d}|jr<|d|jd7}n|d7}|rf|d|jdt|dd7}|r|jprd}|d 7}|d |d 7}|d 7}|S) zE Builds a formatted description of a registered option and prints it  rCzNo description available.z [default: z] [currently: T]rAz (Deprecatedz, use `z ` instead.)) r5rrprGstriprxrLr,r)r+r?rPrIrrrrrD{s  rDP)r&_printc sddlm}ddlmtttttdfdd }g}ddt|D}|r`||d |7}d d|D}xB|t|d d D],\}fd dt|D}|||7}qWd |} |rt | n| SdS)zB Builds a concise listing of available options, grouped by prefix r)groupby)wrap)nameksrcsP|rd|dnd}d||ddd}|rL|drL|rL|dd |d<|S) Nz- z.[rAz, z F)initial_indentsubsequent_indentbreak_long_wordsrsr)rG)rrpfxls)widthrrrppszpp_options_list..ppcSsg|]}|ddkr|qS)rWr)find)rExrrrrFsz#pp_options_list..rAcSsg|]}|ddkr|qS)rWr)r)rErrrrrFscSs|d|dS)NrW)rfind)rrrrz!pp_options_list..cs g|]}|tddqS)r N)r")rEr)r+rrrFsrCN) itertoolsrtextwraprr_rr rr2rGrH) r&rrrrrZsinglesgrrIr)r+rrrrhs     rhc#sNttdfdd }t}t}t}|ta|ta|tadV|a|a|adS)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. )rcrcstdfdd }tt|S)N)r'csd|}|f||S)NrWr)r'r:rdZpkey)rcrQrrinnersz*config_prefix..wrap..inner)r_r r)rcr)rQ)rcrrszconfig_prefix..wrapN)rr get_option set_option)rQrZ_register_optionr,r@r)rQr config_prefixsr)_typercsddfdd }|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)rcs t|krtdddS)NzValue must have type 'r)typer0)r)rrrrs zis_type_factory..innerr)rrr)rris_type_factorysrcsLtttfr(tdttn ddddfdd }|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` |rN)rcst|stddS)NzValue must be an instance of )rYr0)r)r type_reprrrrs z"is_instance_factory..inner)rYtupler2rGmapr_)rrr)rrris_instance_factorys  rcs4ddDddDddfdd }|S)NcSsg|]}t|r|qSr)callable)rEcrrrrFsz%is_one_of_factory..cSsg|]}t|s|qSr)r)rErrrrrF s)rcs\krXtfddDsXddD}d|}d|}trP|d7}t|dS)Nc3s|]}|VqdS)Nr)rEr)rrr %sz3is_one_of_factory..inner..cSsg|] }t|qSr)r_)rEZlvalrrrrF&sz4is_one_of_factory..inner..rzValue must be one of z or a callable)anyrGr"r0)rZuvalsZ pp_valuesr) callables legal_values)rrr"s  z is_one_of_factory..innerr)rrr)rrris_one_of_factorys r)valuercCs2|dkr dSt|tr"|dkr"dSd}t|dS)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 Nrz+Value must be a nonnegative integer or None)rYintr0)rrrrris_nonnegative_int0s rcCst|stddS)z Parameters ---------- `obj` - the object to be checked Returns ------- validator - returns True if object is callable raises ValueError otherwise. zValue must be a callableT)rr0)objrrr is_callableRs r)F)rAT)F)rANN)NNN)rF)Lr collectionsr contextlibrrrytypingrrrrr r r r r r8Zpandas._typingrrrrr___annotations__rrrAttributeErrorr[rboolr(r,r@rJrMrNrOr`Z_get_option_tmplZ_set_option_tmplZ_describe_option_tmplZ_reset_option_tmplrrZ reset_optionZdescribe_optionoptionsrkrRrrr!r)rrr5r%r#rDrhrrrrrrZis_intZis_boolfloatZis_floatZis_strbytesZis_textrrrrr1sr ,     .-"     #(F.   & 5