config.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. """
  2. The config module holds package-wide configurables and provides
  3. a uniform API for working with them.
  4. Overview
  5. ========
  6. This module supports the following requirements:
  7. - options are referenced using keys in dot.notation, e.g. "x.y.option - z".
  8. - keys are case-insensitive.
  9. - functions should accept partial/regex keys, when unambiguous.
  10. - options can be registered by modules at import time.
  11. - options can be registered at init-time (via core.config_init)
  12. - options have a default value, and (optionally) a description and
  13. validation function associated with them.
  14. - options can be deprecated, in which case referencing them
  15. should produce a warning.
  16. - deprecated options can optionally be rerouted to a replacement
  17. so that accessing a deprecated option reroutes to a differently
  18. named option.
  19. - options can be reset to their default value.
  20. - all option can be reset to their default value at once.
  21. - all options in a certain sub - namespace can be reset at once.
  22. - the user can set / get / reset or ask for the description of an option.
  23. - a developer can register and mark an option as deprecated.
  24. - you can register a callback to be invoked when the option value
  25. is set or reset. Changing the stored value is considered misuse, but
  26. is not verboten.
  27. Implementation
  28. ==============
  29. - Data is stored using nested dictionaries, and should be accessed
  30. through the provided API.
  31. - "Registered options" and "Deprecated options" have metadata associated
  32. with them, which are stored in auxiliary dictionaries keyed on the
  33. fully-qualified key, e.g. "x.y.z.option".
  34. - the config_init module is imported by the package's __init__.py file.
  35. placing any register_option() calls there will ensure those options
  36. are available as soon as pandas is loaded. If you use register_option
  37. in a module, it will only be available after that module is imported,
  38. which you should be aware of.
  39. - `config_prefix` is a context_manager (for use with the `with` keyword)
  40. which can save developers some typing, see the docstring.
  41. """
  42. from __future__ import annotations
  43. from contextlib import (
  44. ContextDecorator,
  45. contextmanager,
  46. )
  47. import re
  48. from typing import (
  49. Any,
  50. Callable,
  51. Generator,
  52. Generic,
  53. Iterable,
  54. NamedTuple,
  55. cast,
  56. )
  57. import warnings
  58. from pandas._typing import (
  59. F,
  60. T,
  61. )
  62. from pandas.util._exceptions import find_stack_level
  63. class DeprecatedOption(NamedTuple):
  64. key: str
  65. msg: str | None
  66. rkey: str | None
  67. removal_ver: str | None
  68. class RegisteredOption(NamedTuple):
  69. key: str
  70. defval: object
  71. doc: str
  72. validator: Callable[[object], Any] | None
  73. cb: Callable[[str], Any] | None
  74. # holds deprecated option metadata
  75. _deprecated_options: dict[str, DeprecatedOption] = {}
  76. # holds registered option metadata
  77. _registered_options: dict[str, RegisteredOption] = {}
  78. # holds the current values for registered options
  79. _global_config: dict[str, Any] = {}
  80. # keys which have a special meaning
  81. _reserved_keys: list[str] = ["all"]
  82. class OptionError(AttributeError, KeyError):
  83. """
  84. Exception raised for pandas.options.
  85. Backwards compatible with KeyError checks.
  86. """
  87. #
  88. # User API
  89. def _get_single_key(pat: str, silent: bool) -> str:
  90. keys = _select_options(pat)
  91. if len(keys) == 0:
  92. if not silent:
  93. _warn_if_deprecated(pat)
  94. raise OptionError(f"No such keys(s): {repr(pat)}")
  95. if len(keys) > 1:
  96. raise OptionError("Pattern matched multiple keys")
  97. key = keys[0]
  98. if not silent:
  99. _warn_if_deprecated(key)
  100. key = _translate_key(key)
  101. return key
  102. def _get_option(pat: str, silent: bool = False) -> Any:
  103. key = _get_single_key(pat, silent)
  104. # walk the nested dict
  105. root, k = _get_root(key)
  106. return root[k]
  107. def _set_option(*args, **kwargs) -> None:
  108. # must at least 1 arg deal with constraints later
  109. nargs = len(args)
  110. if not nargs or nargs % 2 != 0:
  111. raise ValueError("Must provide an even number of non-keyword arguments")
  112. # default to false
  113. silent = kwargs.pop("silent", False)
  114. if kwargs:
  115. kwarg = list(kwargs.keys())[0]
  116. raise TypeError(f'_set_option() got an unexpected keyword argument "{kwarg}"')
  117. for k, v in zip(args[::2], args[1::2]):
  118. key = _get_single_key(k, silent)
  119. o = _get_registered_option(key)
  120. if o and o.validator:
  121. o.validator(v)
  122. # walk the nested dict
  123. root, k = _get_root(key)
  124. root[k] = v
  125. if o.cb:
  126. if silent:
  127. with warnings.catch_warnings(record=True):
  128. o.cb(key)
  129. else:
  130. o.cb(key)
  131. def _describe_option(pat: str = "", _print_desc: bool = True) -> str | None:
  132. keys = _select_options(pat)
  133. if len(keys) == 0:
  134. raise OptionError("No such keys(s)")
  135. s = "\n".join([_build_option_description(k) for k in keys])
  136. if _print_desc:
  137. print(s)
  138. return None
  139. return s
  140. def _reset_option(pat: str, silent: bool = False) -> None:
  141. keys = _select_options(pat)
  142. if len(keys) == 0:
  143. raise OptionError("No such keys(s)")
  144. if len(keys) > 1 and len(pat) < 4 and pat != "all":
  145. raise ValueError(
  146. "You must specify at least 4 characters when "
  147. "resetting multiple keys, use the special keyword "
  148. '"all" to reset all the options to their default value'
  149. )
  150. for k in keys:
  151. _set_option(k, _registered_options[k].defval, silent=silent)
  152. def get_default_val(pat: str):
  153. key = _get_single_key(pat, silent=True)
  154. return _get_registered_option(key).defval
  155. class DictWrapper:
  156. """provide attribute-style access to a nested dict"""
  157. def __init__(self, d: dict[str, Any], prefix: str = "") -> None:
  158. object.__setattr__(self, "d", d)
  159. object.__setattr__(self, "prefix", prefix)
  160. def __setattr__(self, key: str, val: Any) -> None:
  161. prefix = object.__getattribute__(self, "prefix")
  162. if prefix:
  163. prefix += "."
  164. prefix += key
  165. # you can't set new keys
  166. # can you can't overwrite subtrees
  167. if key in self.d and not isinstance(self.d[key], dict):
  168. _set_option(prefix, val)
  169. else:
  170. raise OptionError("You can only set the value of existing options")
  171. def __getattr__(self, key: str):
  172. prefix = object.__getattribute__(self, "prefix")
  173. if prefix:
  174. prefix += "."
  175. prefix += key
  176. try:
  177. v = object.__getattribute__(self, "d")[key]
  178. except KeyError as err:
  179. raise OptionError("No such option") from err
  180. if isinstance(v, dict):
  181. return DictWrapper(v, prefix)
  182. else:
  183. return _get_option(prefix)
  184. def __dir__(self) -> Iterable[str]:
  185. return list(self.d.keys())
  186. # For user convenience, we'd like to have the available options described
  187. # in the docstring. For dev convenience we'd like to generate the docstrings
  188. # dynamically instead of maintaining them by hand. To this, we use the
  189. # class below which wraps functions inside a callable, and converts
  190. # __doc__ into a property function. The doctsrings below are templates
  191. # using the py2.6+ advanced formatting syntax to plug in a concise list
  192. # of options, and option descriptions.
  193. class CallableDynamicDoc(Generic[T]):
  194. def __init__(self, func: Callable[..., T], doc_tmpl: str) -> None:
  195. self.__doc_tmpl__ = doc_tmpl
  196. self.__func__ = func
  197. def __call__(self, *args, **kwds) -> T:
  198. return self.__func__(*args, **kwds)
  199. # error: Signature of "__doc__" incompatible with supertype "object"
  200. @property
  201. def __doc__(self) -> str: # type: ignore[override]
  202. opts_desc = _describe_option("all", _print_desc=False)
  203. opts_list = pp_options_list(list(_registered_options.keys()))
  204. return self.__doc_tmpl__.format(opts_desc=opts_desc, opts_list=opts_list)
  205. _get_option_tmpl = """
  206. get_option(pat)
  207. Retrieves the value of the specified option.
  208. Available options:
  209. {opts_list}
  210. Parameters
  211. ----------
  212. pat : str
  213. Regexp which should match a single option.
  214. Note: partial matches are supported for convenience, but unless you use the
  215. full option name (e.g. x.y.z.option_name), your code may break in future
  216. versions if new options with similar names are introduced.
  217. Returns
  218. -------
  219. result : the value of the option
  220. Raises
  221. ------
  222. OptionError : if no such option exists
  223. Notes
  224. -----
  225. Please reference the :ref:`User Guide <options>` for more information.
  226. The available options with its descriptions:
  227. {opts_desc}
  228. """
  229. _set_option_tmpl = """
  230. set_option(pat, value)
  231. Sets the value of the specified option.
  232. Available options:
  233. {opts_list}
  234. Parameters
  235. ----------
  236. pat : str
  237. Regexp which should match a single option.
  238. Note: partial matches are supported for convenience, but unless you use the
  239. full option name (e.g. x.y.z.option_name), your code may break in future
  240. versions if new options with similar names are introduced.
  241. value : object
  242. New value of option.
  243. Returns
  244. -------
  245. None
  246. Raises
  247. ------
  248. OptionError if no such option exists
  249. Notes
  250. -----
  251. Please reference the :ref:`User Guide <options>` for more information.
  252. The available options with its descriptions:
  253. {opts_desc}
  254. """
  255. _describe_option_tmpl = """
  256. describe_option(pat, _print_desc=False)
  257. Prints the description for one or more registered options.
  258. Call with no arguments to get a listing for all registered options.
  259. Available options:
  260. {opts_list}
  261. Parameters
  262. ----------
  263. pat : str
  264. Regexp pattern. All matching keys will have their description displayed.
  265. _print_desc : bool, default True
  266. If True (default) the description(s) will be printed to stdout.
  267. Otherwise, the description(s) will be returned as a unicode string
  268. (for testing).
  269. Returns
  270. -------
  271. None by default, the description(s) as a unicode string if _print_desc
  272. is False
  273. Notes
  274. -----
  275. Please reference the :ref:`User Guide <options>` for more information.
  276. The available options with its descriptions:
  277. {opts_desc}
  278. """
  279. _reset_option_tmpl = """
  280. reset_option(pat)
  281. Reset one or more options to their default value.
  282. Pass "all" as argument to reset all options.
  283. Available options:
  284. {opts_list}
  285. Parameters
  286. ----------
  287. pat : str/regex
  288. If specified only options matching `prefix*` will be reset.
  289. Note: partial matches are supported for convenience, but unless you
  290. use the full option name (e.g. x.y.z.option_name), your code may break
  291. in future versions if new options with similar names are introduced.
  292. Returns
  293. -------
  294. None
  295. Notes
  296. -----
  297. Please reference the :ref:`User Guide <options>` for more information.
  298. The available options with its descriptions:
  299. {opts_desc}
  300. """
  301. # bind the functions with their docstrings into a Callable
  302. # and use that as the functions exposed in pd.api
  303. get_option = CallableDynamicDoc(_get_option, _get_option_tmpl)
  304. set_option = CallableDynamicDoc(_set_option, _set_option_tmpl)
  305. reset_option = CallableDynamicDoc(_reset_option, _reset_option_tmpl)
  306. describe_option = CallableDynamicDoc(_describe_option, _describe_option_tmpl)
  307. options = DictWrapper(_global_config)
  308. #
  309. # Functions for use by pandas developers, in addition to User - api
  310. class option_context(ContextDecorator):
  311. """
  312. Context manager to temporarily set options in the `with` statement context.
  313. You need to invoke as ``option_context(pat, val, [(pat, val), ...])``.
  314. Examples
  315. --------
  316. >>> from pandas import option_context
  317. >>> with option_context('display.max_rows', 10, 'display.max_columns', 5):
  318. ... pass
  319. """
  320. def __init__(self, *args) -> None:
  321. if len(args) % 2 != 0 or len(args) < 2:
  322. raise ValueError(
  323. "Need to invoke as option_context(pat, val, [(pat, val), ...])."
  324. )
  325. self.ops = list(zip(args[::2], args[1::2]))
  326. def __enter__(self) -> None:
  327. self.undo = [(pat, _get_option(pat, silent=True)) for pat, val in self.ops]
  328. for pat, val in self.ops:
  329. _set_option(pat, val, silent=True)
  330. def __exit__(self, *args) -> None:
  331. if self.undo:
  332. for pat, val in self.undo:
  333. _set_option(pat, val, silent=True)
  334. def register_option(
  335. key: str,
  336. defval: object,
  337. doc: str = "",
  338. validator: Callable[[object], Any] | None = None,
  339. cb: Callable[[str], Any] | None = None,
  340. ) -> None:
  341. """
  342. Register an option in the package-wide pandas config object
  343. Parameters
  344. ----------
  345. key : str
  346. Fully-qualified key, e.g. "x.y.option - z".
  347. defval : object
  348. Default value of the option.
  349. doc : str
  350. Description of the option.
  351. validator : Callable, optional
  352. Function of a single argument, should raise `ValueError` if
  353. called with a value which is not a legal value for the option.
  354. cb
  355. a function of a single argument "key", which is called
  356. immediately after an option value is set/reset. key is
  357. the full name of the option.
  358. Raises
  359. ------
  360. ValueError if `validator` is specified and `defval` is not a valid value.
  361. """
  362. import keyword
  363. import tokenize
  364. key = key.lower()
  365. if key in _registered_options:
  366. raise OptionError(f"Option '{key}' has already been registered")
  367. if key in _reserved_keys:
  368. raise OptionError(f"Option '{key}' is a reserved key")
  369. # the default value should be legal
  370. if validator:
  371. validator(defval)
  372. # walk the nested dict, creating dicts as needed along the path
  373. path = key.split(".")
  374. for k in path:
  375. if not re.match("^" + tokenize.Name + "$", k):
  376. raise ValueError(f"{k} is not a valid identifier")
  377. if keyword.iskeyword(k):
  378. raise ValueError(f"{k} is a python keyword")
  379. cursor = _global_config
  380. msg = "Path prefix to option '{option}' is already an option"
  381. for i, p in enumerate(path[:-1]):
  382. if not isinstance(cursor, dict):
  383. raise OptionError(msg.format(option=".".join(path[:i])))
  384. if p not in cursor:
  385. cursor[p] = {}
  386. cursor = cursor[p]
  387. if not isinstance(cursor, dict):
  388. raise OptionError(msg.format(option=".".join(path[:-1])))
  389. cursor[path[-1]] = defval # initialize
  390. # save the option metadata
  391. _registered_options[key] = RegisteredOption(
  392. key=key, defval=defval, doc=doc, validator=validator, cb=cb
  393. )
  394. def deprecate_option(
  395. key: str,
  396. msg: str | None = None,
  397. rkey: str | None = None,
  398. removal_ver: str | None = None,
  399. ) -> None:
  400. """
  401. Mark option `key` as deprecated, if code attempts to access this option,
  402. a warning will be produced, using `msg` if given, or a default message
  403. if not.
  404. if `rkey` is given, any access to the key will be re-routed to `rkey`.
  405. Neither the existence of `key` nor that if `rkey` is checked. If they
  406. do not exist, any subsequence access will fail as usual, after the
  407. deprecation warning is given.
  408. Parameters
  409. ----------
  410. key : str
  411. Name of the option to be deprecated.
  412. must be a fully-qualified option name (e.g "x.y.z.rkey").
  413. msg : str, optional
  414. Warning message to output when the key is referenced.
  415. if no message is given a default message will be emitted.
  416. rkey : str, optional
  417. Name of an option to reroute access to.
  418. If specified, any referenced `key` will be
  419. re-routed to `rkey` including set/get/reset.
  420. rkey must be a fully-qualified option name (e.g "x.y.z.rkey").
  421. used by the default message if no `msg` is specified.
  422. removal_ver : str, optional
  423. Specifies the version in which this option will
  424. be removed. used by the default message if no `msg` is specified.
  425. Raises
  426. ------
  427. OptionError
  428. If the specified key has already been deprecated.
  429. """
  430. key = key.lower()
  431. if key in _deprecated_options:
  432. raise OptionError(f"Option '{key}' has already been defined as deprecated.")
  433. _deprecated_options[key] = DeprecatedOption(key, msg, rkey, removal_ver)
  434. #
  435. # functions internal to the module
  436. def _select_options(pat: str) -> list[str]:
  437. """
  438. returns a list of keys matching `pat`
  439. if pat=="all", returns all registered options
  440. """
  441. # short-circuit for exact key
  442. if pat in _registered_options:
  443. return [pat]
  444. # else look through all of them
  445. keys = sorted(_registered_options.keys())
  446. if pat == "all": # reserved key
  447. return keys
  448. return [k for k in keys if re.search(pat, k, re.I)]
  449. def _get_root(key: str) -> tuple[dict[str, Any], str]:
  450. path = key.split(".")
  451. cursor = _global_config
  452. for p in path[:-1]:
  453. cursor = cursor[p]
  454. return cursor, path[-1]
  455. def _is_deprecated(key: str) -> bool:
  456. """Returns True if the given option has been deprecated"""
  457. key = key.lower()
  458. return key in _deprecated_options
  459. def _get_deprecated_option(key: str):
  460. """
  461. Retrieves the metadata for a deprecated option, if `key` is deprecated.
  462. Returns
  463. -------
  464. DeprecatedOption (namedtuple) if key is deprecated, None otherwise
  465. """
  466. try:
  467. d = _deprecated_options[key]
  468. except KeyError:
  469. return None
  470. else:
  471. return d
  472. def _get_registered_option(key: str):
  473. """
  474. Retrieves the option metadata if `key` is a registered option.
  475. Returns
  476. -------
  477. RegisteredOption (namedtuple) if key is deprecated, None otherwise
  478. """
  479. return _registered_options.get(key)
  480. def _translate_key(key: str) -> str:
  481. """
  482. if key id deprecated and a replacement key defined, will return the
  483. replacement key, otherwise returns `key` as - is
  484. """
  485. d = _get_deprecated_option(key)
  486. if d:
  487. return d.rkey or key
  488. else:
  489. return key
  490. def _warn_if_deprecated(key: str) -> bool:
  491. """
  492. Checks if `key` is a deprecated option and if so, prints a warning.
  493. Returns
  494. -------
  495. bool - True if `key` is deprecated, False otherwise.
  496. """
  497. d = _get_deprecated_option(key)
  498. if d:
  499. if d.msg:
  500. warnings.warn(
  501. d.msg,
  502. FutureWarning,
  503. stacklevel=find_stack_level(),
  504. )
  505. else:
  506. msg = f"'{key}' is deprecated"
  507. if d.removal_ver:
  508. msg += f" and will be removed in {d.removal_ver}"
  509. if d.rkey:
  510. msg += f", please use '{d.rkey}' instead."
  511. else:
  512. msg += ", please refrain from using it."
  513. warnings.warn(msg, FutureWarning, stacklevel=find_stack_level())
  514. return True
  515. return False
  516. def _build_option_description(k: str) -> str:
  517. """Builds a formatted description of a registered option and prints it"""
  518. o = _get_registered_option(k)
  519. d = _get_deprecated_option(k)
  520. s = f"{k} "
  521. if o.doc:
  522. s += "\n".join(o.doc.strip().split("\n"))
  523. else:
  524. s += "No description available."
  525. if o:
  526. s += f"\n [default: {o.defval}] [currently: {_get_option(k, True)}]"
  527. if d:
  528. rkey = d.rkey or ""
  529. s += "\n (Deprecated"
  530. s += f", use `{rkey}` instead."
  531. s += ")"
  532. return s
  533. def pp_options_list(keys: Iterable[str], width: int = 80, _print: bool = False):
  534. """Builds a concise listing of available options, grouped by prefix"""
  535. from itertools import groupby
  536. from textwrap import wrap
  537. def pp(name: str, ks: Iterable[str]) -> list[str]:
  538. pfx = "- " + name + ".[" if name else ""
  539. ls = wrap(
  540. ", ".join(ks),
  541. width,
  542. initial_indent=pfx,
  543. subsequent_indent=" ",
  544. break_long_words=False,
  545. )
  546. if ls and ls[-1] and name:
  547. ls[-1] = ls[-1] + "]"
  548. return ls
  549. ls: list[str] = []
  550. singles = [x for x in sorted(keys) if x.find(".") < 0]
  551. if singles:
  552. ls += pp("", singles)
  553. keys = [x for x in keys if x.find(".") >= 0]
  554. for k, g in groupby(sorted(keys), lambda x: x[: x.rfind(".")]):
  555. ks = [x[len(k) + 1 :] for x in list(g)]
  556. ls += pp(k, ks)
  557. s = "\n".join(ls)
  558. if _print:
  559. print(s)
  560. else:
  561. return s
  562. #
  563. # helpers
  564. @contextmanager
  565. def config_prefix(prefix) -> Generator[None, None, None]:
  566. """
  567. contextmanager for multiple invocations of API with a common prefix
  568. supported API functions: (register / get / set )__option
  569. Warning: This is not thread - safe, and won't work properly if you import
  570. the API functions into your module using the "from x import y" construct.
  571. Example
  572. -------
  573. import pandas._config.config as cf
  574. with cf.config_prefix("display.font"):
  575. cf.register_option("color", "red")
  576. cf.register_option("size", " 5 pt")
  577. cf.set_option(size, " 6 pt")
  578. cf.get_option(size)
  579. ...
  580. etc'
  581. will register options "display.font.color", "display.font.size", set the
  582. value of "display.font.size"... and so on.
  583. """
  584. # Note: reset_option relies on set_option, and on key directly
  585. # it does not fit in to this monkey-patching scheme
  586. global register_option, get_option, set_option
  587. def wrap(func: F) -> F:
  588. def inner(key: str, *args, **kwds):
  589. pkey = f"{prefix}.{key}"
  590. return func(pkey, *args, **kwds)
  591. return cast(F, inner)
  592. _register_option = register_option
  593. _get_option = get_option
  594. _set_option = set_option
  595. set_option = wrap(set_option)
  596. get_option = wrap(get_option)
  597. register_option = wrap(register_option)
  598. try:
  599. yield
  600. finally:
  601. set_option = _set_option
  602. get_option = _get_option
  603. register_option = _register_option
  604. # These factories and methods are handy for use as the validator
  605. # arg in register_option
  606. def is_type_factory(_type: type[Any]) -> Callable[[Any], None]:
  607. """
  608. Parameters
  609. ----------
  610. `_type` - a type to be compared against (e.g. type(x) == `_type`)
  611. Returns
  612. -------
  613. validator - a function of a single argument x , which raises
  614. ValueError if type(x) is not equal to `_type`
  615. """
  616. def inner(x) -> None:
  617. if type(x) != _type:
  618. raise ValueError(f"Value must have type '{_type}'")
  619. return inner
  620. def is_instance_factory(_type) -> Callable[[Any], None]:
  621. """
  622. Parameters
  623. ----------
  624. `_type` - the type to be checked against
  625. Returns
  626. -------
  627. validator - a function of a single argument x , which raises
  628. ValueError if x is not an instance of `_type`
  629. """
  630. if isinstance(_type, (tuple, list)):
  631. _type = tuple(_type)
  632. type_repr = "|".join(map(str, _type))
  633. else:
  634. type_repr = f"'{_type}'"
  635. def inner(x) -> None:
  636. if not isinstance(x, _type):
  637. raise ValueError(f"Value must be an instance of {type_repr}")
  638. return inner
  639. def is_one_of_factory(legal_values) -> Callable[[Any], None]:
  640. callables = [c for c in legal_values if callable(c)]
  641. legal_values = [c for c in legal_values if not callable(c)]
  642. def inner(x) -> None:
  643. if x not in legal_values:
  644. if not any(c(x) for c in callables):
  645. uvals = [str(lval) for lval in legal_values]
  646. pp_values = "|".join(uvals)
  647. msg = f"Value must be one of {pp_values}"
  648. if len(callables):
  649. msg += " or a callable"
  650. raise ValueError(msg)
  651. return inner
  652. def is_nonnegative_int(value: object) -> None:
  653. """
  654. Verify that value is None or a positive int.
  655. Parameters
  656. ----------
  657. value : None or int
  658. The `value` to be checked.
  659. Raises
  660. ------
  661. ValueError
  662. When the value is not None or is a negative integer
  663. """
  664. if value is None:
  665. return
  666. elif isinstance(value, int):
  667. if value >= 0:
  668. return
  669. msg = "Value must be a nonnegative integer or None"
  670. raise ValueError(msg)
  671. # common type validators, for convenience
  672. # usage: register_option(... , validator = is_int)
  673. is_int = is_type_factory(int)
  674. is_bool = is_type_factory(bool)
  675. is_float = is_type_factory(float)
  676. is_str = is_type_factory(str)
  677. is_text = is_instance_factory((str, bytes))
  678. def is_callable(obj) -> bool:
  679. """
  680. Parameters
  681. ----------
  682. `obj` - the object to be checked
  683. Returns
  684. -------
  685. validator - returns True if object is callable
  686. raises ValueError otherwise.
  687. """
  688. if not callable(obj):
  689. raise ValueError("Value must be a callable")
  690. return True