5151from collections import namedtuple
5252from contextlib import contextmanager
5353import re
54- from typing import Any , Dict , Iterable , List
54+ from typing import (
55+ Any ,
56+ Callable ,
57+ Dict ,
58+ Iterable ,
59+ List ,
60+ Optional ,
61+ Tuple ,
62+ Type ,
63+ TypeVar ,
64+ cast ,
65+ )
5566import warnings
5667
5768DeprecatedOption = namedtuple ("DeprecatedOption" , "key msg rkey removal_ver" )
@@ -80,7 +91,7 @@ class OptionError(AttributeError, KeyError):
8091# User API
8192
8293
83- def _get_single_key (pat , silent ) :
94+ def _get_single_key (pat : str , silent : bool ) -> str :
8495 keys = _select_options (pat )
8596 if len (keys ) == 0 :
8697 if not silent :
@@ -98,15 +109,15 @@ def _get_single_key(pat, silent):
98109 return key
99110
100111
101- def _get_option (pat , silent = False ):
112+ def _get_option (pat : str , silent : bool = False ):
102113 key = _get_single_key (pat , silent )
103114
104115 # walk the nested dict
105116 root , k = _get_root (key )
106117 return root [k ]
107118
108119
109- def _set_option (* args , ** kwargs ):
120+ def _set_option (* args , ** kwargs ) -> None :
110121 # must at least 1 arg deal with constraints later
111122 nargs = len (args )
112123 if not nargs or nargs % 2 != 0 :
@@ -138,7 +149,7 @@ def _set_option(*args, **kwargs):
138149 o .cb (key )
139150
140151
141- def _describe_option (pat = "" , _print_desc = True ):
152+ def _describe_option (pat : str = "" , _print_desc : bool = True ):
142153
143154 keys = _select_options (pat )
144155 if len (keys ) == 0 :
@@ -154,7 +165,7 @@ def _describe_option(pat="", _print_desc=True):
154165 return s
155166
156167
157- def _reset_option (pat , silent = False ):
168+ def _reset_option (pat : str , silent : bool = False ) -> None :
158169
159170 keys = _select_options (pat )
160171
@@ -172,19 +183,19 @@ def _reset_option(pat, silent=False):
172183 _set_option (k , _registered_options [k ].defval , silent = silent )
173184
174185
175- def get_default_val (pat ):
186+ def get_default_val (pat : str ):
176187 key = _get_single_key (pat , silent = True )
177188 return _get_registered_option (key ).defval
178189
179190
180191class DictWrapper :
181192 """ provide attribute-style access to a nested dict"""
182193
183- def __init__ (self , d , prefix = "" ):
194+ def __init__ (self , d : Dict [ str , Any ], prefix : str = "" ):
184195 object .__setattr__ (self , "d" , d )
185196 object .__setattr__ (self , "prefix" , prefix )
186197
187- def __setattr__ (self , key , val ) :
198+ def __setattr__ (self , key : str , val : Any ) -> None :
188199 prefix = object .__getattribute__ (self , "prefix" )
189200 if prefix :
190201 prefix += "."
@@ -210,7 +221,7 @@ def __getattr__(self, key: str):
210221 else :
211222 return _get_option (prefix )
212223
213- def __dir__ (self ):
224+ def __dir__ (self ) -> Iterable [ str ] :
214225 return list (self .d .keys ())
215226
216227
@@ -411,23 +422,31 @@ def __exit__(self, *args):
411422 _set_option (pat , val , silent = True )
412423
413424
414- def register_option (key : str , defval : object , doc = "" , validator = None , cb = None ):
415- """Register an option in the package-wide pandas config object
425+ def register_option (
426+ key : str ,
427+ defval : object ,
428+ doc : str = "" ,
429+ validator : Optional [Callable [[Any ], Any ]] = None ,
430+ cb : Optional [Callable [[str ], Any ]] = None ,
431+ ) -> None :
432+ """
433+ Register an option in the package-wide pandas config object
416434
417435 Parameters
418436 ----------
419- key - a fully-qualified key, e.g. "x.y.option - z".
420- defval - the default value of the option
421- doc - a string description of the option
422- validator - a function of a single argument, should raise `ValueError` if
423- called with a value which is not a legal value for the option.
424- cb - a function of a single argument "key", which is called
425- immediately after an option value is set/reset. key is
426- the full name of the option.
427-
428- Returns
429- -------
430- Nothing.
437+ key : str
438+ Fully-qualified key, e.g. "x.y.option - z".
439+ defval : object
440+ Default value of the option.
441+ doc : str
442+ Description of the option.
443+ validator : Callable, optional
444+ Function of a single argument, should raise `ValueError` if
445+ called with a value which is not a legal value for the option.
446+ cb
447+ a function of a single argument "key", which is called
448+ immediately after an option value is set/reset. key is
449+ the full name of the option.
431450
432451 Raises
433452 ------
@@ -480,7 +499,9 @@ def register_option(key: str, defval: object, doc="", validator=None, cb=None):
480499 )
481500
482501
483- def deprecate_option (key , msg = None , rkey = None , removal_ver = None ):
502+ def deprecate_option (
503+ key : str , msg : Optional [str ] = None , rkey : Optional [str ] = None , removal_ver = None
504+ ) -> None :
484505 """
485506 Mark option `key` as deprecated, if code attempts to access this option,
486507 a warning will be produced, using `msg` if given, or a default message
@@ -493,32 +514,27 @@ def deprecate_option(key, msg=None, rkey=None, removal_ver=None):
493514
494515 Parameters
495516 ----------
496- key - the name of the option to be deprecated. must be a fully-qualified
497- option name (e.g "x.y.z.rkey").
498-
499- msg - (Optional) a warning message to output when the key is referenced.
500- if no message is given a default message will be emitted.
501-
502- rkey - (Optional) the name of an option to reroute access to.
503- If specified, any referenced `key` will be re-routed to `rkey`
504- including set/get/reset.
505- rkey must be a fully-qualified option name (e.g "x.y.z.rkey").
506- used by the default message if no `msg` is specified.
507-
508- removal_ver - (Optional) specifies the version in which this option will
509- be removed. used by the default message if no `msg`
510- is specified.
511-
512- Returns
513- -------
514- Nothing
517+ key : str
518+ Name of the option to be deprecated.
519+ must be a fully-qualified option name (e.g "x.y.z.rkey").
520+ msg : str, optional
521+ Warning message to output when the key is referenced.
522+ if no message is given a default message will be emitted.
523+ rkey : str, optional
524+ Name of an option to reroute access to.
525+ If specified, any referenced `key` will be
526+ re-routed to `rkey` including set/get/reset.
527+ rkey must be a fully-qualified option name (e.g "x.y.z.rkey").
528+ used by the default message if no `msg` is specified.
529+ removal_ver : optional
530+ Specifies the version in which this option will
531+ be removed. used by the default message if no `msg` is specified.
515532
516533 Raises
517534 ------
518- OptionError - if key has already been deprecated.
519-
535+ OptionError
536+ If the specified key has already been deprecated.
520537 """
521-
522538 key = key .lower ()
523539
524540 if key in _deprecated_options :
@@ -531,7 +547,7 @@ def deprecate_option(key, msg=None, rkey=None, removal_ver=None):
531547# functions internal to the module
532548
533549
534- def _select_options (pat ) :
550+ def _select_options (pat : str ) -> List [ str ] :
535551 """returns a list of keys matching `pat`
536552
537553 if pat=="all", returns all registered options
@@ -549,22 +565,22 @@ def _select_options(pat):
549565 return [k for k in keys if re .search (pat , k , re .I )]
550566
551567
552- def _get_root (key ) :
568+ def _get_root (key : str ) -> Tuple [ Dict [ str , Any ], str ] :
553569 path = key .split ("." )
554570 cursor = _global_config
555571 for p in path [:- 1 ]:
556572 cursor = cursor [p ]
557573 return cursor , path [- 1 ]
558574
559575
560- def _is_deprecated (key ) :
576+ def _is_deprecated (key : str ) -> bool :
561577 """ Returns True if the given option has been deprecated """
562578
563579 key = key .lower ()
564580 return key in _deprecated_options
565581
566582
567- def _get_deprecated_option (key ):
583+ def _get_deprecated_option (key : str ):
568584 """
569585 Retrieves the metadata for a deprecated option, if `key` is deprecated.
570586
@@ -581,7 +597,7 @@ def _get_deprecated_option(key):
581597 return d
582598
583599
584- def _get_registered_option (key ):
600+ def _get_registered_option (key : str ):
585601 """
586602 Retrieves the option metadata if `key` is a registered option.
587603
@@ -592,7 +608,7 @@ def _get_registered_option(key):
592608 return _registered_options .get (key )
593609
594610
595- def _translate_key (key ) :
611+ def _translate_key (key : str ) -> str :
596612 """
597613 if key id deprecated and a replacement key defined, will return the
598614 replacement key, otherwise returns `key` as - is
@@ -605,7 +621,7 @@ def _translate_key(key):
605621 return key
606622
607623
608- def _warn_if_deprecated (key ) :
624+ def _warn_if_deprecated (key : str ) -> bool :
609625 """
610626 Checks if `key` is a deprecated option and if so, prints a warning.
611627
@@ -633,7 +649,7 @@ def _warn_if_deprecated(key):
633649 return False
634650
635651
636- def _build_option_description (k ) :
652+ def _build_option_description (k : str ) -> str :
637653 """ Builds a formatted description of a registered option and prints it """
638654
639655 o = _get_registered_option (k )
@@ -658,7 +674,7 @@ def _build_option_description(k):
658674 return s
659675
660676
661- def pp_options_list (keys , width = 80 , _print = False ):
677+ def pp_options_list (keys : Iterable [ str ] , width = 80 , _print : bool = False ):
662678 """ Builds a concise listing of available options, grouped by prefix """
663679
664680 from textwrap import wrap
@@ -696,6 +712,9 @@ def pp(name: str, ks: Iterable[str]) -> List[str]:
696712#
697713# helpers
698714
715+ FuncType = Callable [..., Any ]
716+ F = TypeVar ("F" , bound = FuncType )
717+
699718
700719@contextmanager
701720def config_prefix (prefix ):
@@ -727,12 +746,12 @@ def config_prefix(prefix):
727746
728747 global register_option , get_option , set_option , reset_option
729748
730- def wrap (func ) :
731- def inner (key , * args , ** kwds ):
749+ def wrap (func : F ) -> F :
750+ def inner (key : str , * args , ** kwds ):
732751 pkey = f"{ prefix } .{ key } "
733752 return func (pkey , * args , ** kwds )
734753
735- return inner
754+ return cast ( F , inner )
736755
737756 _register_option = register_option
738757 _get_option = get_option
@@ -750,7 +769,7 @@ def inner(key, *args, **kwds):
750769# arg in register_option
751770
752771
753- def is_type_factory (_type ) :
772+ def is_type_factory (_type : Type [ Any ]) -> Callable [[ Any ], None ] :
754773 """
755774
756775 Parameters
@@ -764,14 +783,14 @@ def is_type_factory(_type):
764783
765784 """
766785
767- def inner (x ):
786+ def inner (x ) -> None :
768787 if type (x ) != _type :
769788 raise ValueError (f"Value must have type '{ _type } '" )
770789
771790 return inner
772791
773792
774- def is_instance_factory (_type ):
793+ def is_instance_factory (_type ) -> Callable [[ Any ], None ] :
775794 """
776795
777796 Parameters
@@ -791,19 +810,19 @@ def is_instance_factory(_type):
791810 else :
792811 type_repr = f"'{ _type } '"
793812
794- def inner (x ):
813+ def inner (x ) -> None :
795814 if not isinstance (x , _type ):
796815 raise ValueError (f"Value must be an instance of { type_repr } " )
797816
798817 return inner
799818
800819
801- def is_one_of_factory (legal_values ):
820+ def is_one_of_factory (legal_values ) -> Callable [[ Any ], None ] :
802821
803822 callables = [c for c in legal_values if callable (c )]
804823 legal_values = [c for c in legal_values if not callable (c )]
805824
806- def inner (x ):
825+ def inner (x ) -> None :
807826 if x not in legal_values :
808827
809828 if not any (c (x ) for c in callables ):
@@ -817,7 +836,7 @@ def inner(x):
817836 return inner
818837
819838
820- def is_nonnegative_int (value ) :
839+ def is_nonnegative_int (value : Optional [ int ]) -> None :
821840 """
822841 Verify that value is None or a positive int.
823842
@@ -852,7 +871,7 @@ def is_nonnegative_int(value):
852871is_text = is_instance_factory ((str , bytes ))
853872
854873
855- def is_callable (obj ):
874+ def is_callable (obj ) -> bool :
856875 """
857876
858877 Parameters
0 commit comments