config.py 23 KB

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