Skip to content

Commit 3a37464

Browse files
simonjayhawkinsjreback
authored andcommitted
TYP: some types for pandas/_config/config.py (#29897)
1 parent 0056143 commit 3a37464

File tree

1 file changed

+27
-32
lines changed

1 file changed

+27
-32
lines changed

pandas/_config/config.py

+27-32
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@
5151
from collections import namedtuple
5252
from contextlib import contextmanager
5353
import re
54-
from typing import Dict, List
54+
from typing import Any, Dict, Iterable, List
5555
import warnings
5656

5757
DeprecatedOption = namedtuple("DeprecatedOption", "key msg rkey removal_ver")
@@ -64,7 +64,7 @@
6464
_registered_options: Dict[str, RegisteredOption] = {}
6565

6666
# holds the current values for registered options
67-
_global_config: Dict[str, str] = {}
67+
_global_config: Dict[str, Any] = {}
6868

6969
# keys which have a special meaning
7070
_reserved_keys: List[str] = ["all"]
@@ -85,7 +85,7 @@ def _get_single_key(pat, silent):
8585
if len(keys) == 0:
8686
if not silent:
8787
_warn_if_deprecated(pat)
88-
raise OptionError("No such keys(s): {pat!r}".format(pat=pat))
88+
raise OptionError(f"No such keys(s): {repr(pat)}")
8989
if len(keys) > 1:
9090
raise OptionError("Pattern matched multiple keys")
9191
key = keys[0]
@@ -116,8 +116,8 @@ def _set_option(*args, **kwargs):
116116
silent = kwargs.pop("silent", False)
117117

118118
if kwargs:
119-
msg = '_set_option() got an unexpected keyword argument "{kwarg}"'
120-
raise TypeError(msg.format(list(kwargs.keys())[0]))
119+
kwarg = list(kwargs.keys())[0]
120+
raise TypeError(f'_set_option() got an unexpected keyword argument "{kwarg}"')
121121

122122
for k, v in zip(args[::2], args[1::2]):
123123
key = _get_single_key(k, silent)
@@ -412,7 +412,7 @@ def __exit__(self, *args):
412412
_set_option(pat, val, silent=True)
413413

414414

415-
def register_option(key, defval, doc="", validator=None, cb=None):
415+
def register_option(key: str, defval: object, doc="", validator=None, cb=None):
416416
"""Register an option in the package-wide pandas config object
417417
418418
Parameters
@@ -441,11 +441,9 @@ def register_option(key, defval, doc="", validator=None, cb=None):
441441
key = key.lower()
442442

443443
if key in _registered_options:
444-
msg = "Option '{key}' has already been registered"
445-
raise OptionError(msg.format(key=key))
444+
raise OptionError(f"Option '{key}' has already been registered")
446445
if key in _reserved_keys:
447-
msg = "Option '{key}' is a reserved key"
448-
raise OptionError(msg.format(key=key))
446+
raise OptionError(f"Option '{key}' is a reserved key")
449447

450448
# the default value should be legal
451449
if validator:
@@ -455,10 +453,12 @@ def register_option(key, defval, doc="", validator=None, cb=None):
455453
path = key.split(".")
456454

457455
for k in path:
458-
if not bool(re.match("^" + tokenize.Name + "$", k)):
459-
raise ValueError("{k} is not a valid identifier".format(k=k))
456+
# NOTE: tokenize.Name is not a public constant
457+
# error: Module has no attribute "Name" [attr-defined]
458+
if not re.match("^" + tokenize.Name + "$", k): # type: ignore
459+
raise ValueError(f"{k} is not a valid identifier")
460460
if keyword.iskeyword(k):
461-
raise ValueError("{k} is a python keyword".format(k=k))
461+
raise ValueError(f"{k} is a python keyword")
462462

463463
cursor = _global_config
464464
msg = "Path prefix to option '{option}' is already an option"
@@ -522,8 +522,7 @@ def deprecate_option(key, msg=None, rkey=None, removal_ver=None):
522522
key = key.lower()
523523

524524
if key in _deprecated_options:
525-
msg = "Option '{key}' has already been defined as deprecated."
526-
raise OptionError(msg.format(key=key))
525+
raise OptionError(f"Option '{key}' has already been defined as deprecated.")
527526

528527
_deprecated_options[key] = DeprecatedOption(key, msg, rkey, removal_ver)
529528

@@ -621,11 +620,11 @@ def _warn_if_deprecated(key):
621620
print(d.msg)
622621
warnings.warn(d.msg, FutureWarning)
623622
else:
624-
msg = "'{key}' is deprecated".format(key=key)
623+
msg = f"'{key}' is deprecated"
625624
if d.removal_ver:
626-
msg += " and will be removed in {version}".format(version=d.removal_ver)
625+
msg += f" and will be removed in {d.removal_ver}"
627626
if d.rkey:
628-
msg += ", please use '{rkey}' instead.".format(rkey=d.rkey)
627+
msg += f", please use '{d.rkey}' instead."
629628
else:
630629
msg += ", please refrain from using it."
631630

@@ -640,17 +639,15 @@ def _build_option_description(k):
640639
o = _get_registered_option(k)
641640
d = _get_deprecated_option(k)
642641

643-
s = "{k} ".format(k=k)
642+
s = f"{k} "
644643

645644
if o.doc:
646645
s += "\n".join(o.doc.strip().split("\n"))
647646
else:
648647
s += "No description available."
649648

650649
if o:
651-
s += "\n [default: {default}] [currently: {current}]".format(
652-
default=o.defval, current=_get_option(k, True)
653-
)
650+
s += f"\n [default: {o.defval}] [currently: {_get_option(k, True)}]"
654651

655652
if d:
656653
s += "\n (Deprecated"
@@ -666,7 +663,7 @@ def pp_options_list(keys, width=80, _print=False):
666663
from textwrap import wrap
667664
from itertools import groupby
668665

669-
def pp(name, ks):
666+
def pp(name: str, ks: Iterable[str]) -> List[str]:
670667
pfx = "- " + name + ".[" if name else ""
671668
ls = wrap(
672669
", ".join(ks),
@@ -679,7 +676,7 @@ def pp(name, ks):
679676
ls[-1] = ls[-1] + "]"
680677
return ls
681678

682-
ls = []
679+
ls: List[str] = []
683680
singles = [x for x in sorted(keys) if x.find(".") < 0]
684681
if singles:
685682
ls += pp("", singles)
@@ -731,7 +728,7 @@ def config_prefix(prefix):
731728

732729
def wrap(func):
733730
def inner(key, *args, **kwds):
734-
pkey = "{prefix}.{key}".format(prefix=prefix, key=key)
731+
pkey = f"{prefix}.{key}"
735732
return func(pkey, *args, **kwds)
736733

737734
return inner
@@ -768,8 +765,7 @@ def is_type_factory(_type):
768765

769766
def inner(x):
770767
if type(x) != _type:
771-
msg = "Value must have type '{typ!s}'"
772-
raise ValueError(msg.format(typ=_type))
768+
raise ValueError(f"Value must have type '{_type}'")
773769

774770
return inner
775771

@@ -792,12 +788,11 @@ def is_instance_factory(_type):
792788
_type = tuple(_type)
793789
type_repr = "|".join(map(str, _type))
794790
else:
795-
type_repr = "'{typ}'".format(typ=_type)
791+
type_repr = f"'{_type}'"
796792

797793
def inner(x):
798794
if not isinstance(x, _type):
799-
msg = "Value must be an instance of {type_repr}"
800-
raise ValueError(msg.format(type_repr=type_repr))
795+
raise ValueError(f"Value must be an instance of {type_repr}")
801796

802797
return inner
803798

@@ -813,10 +808,10 @@ def inner(x):
813808
if not any(c(x) for c in callables):
814809
uvals = [str(lval) for lval in legal_values]
815810
pp_values = "|".join(uvals)
816-
msg = "Value must be one of {pp_values}"
811+
msg = f"Value must be one of {pp_values}"
817812
if len(callables):
818813
msg += " or a callable"
819-
raise ValueError(msg.format(pp_values=pp_values))
814+
raise ValueError(msg)
820815

821816
return inner
822817

0 commit comments

Comments
 (0)