configs.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. import collections
  2. import typing
  3. from dataclasses import dataclass
  4. __all__ = ["Config"]
  5. @dataclass(init=False, eq=False, slots=True, kw_only=True, match_args=False)
  6. class Config:
  7. """The base class for NetworkX configuration.
  8. There are two ways to use this to create configurations. The recommended way
  9. is to subclass ``Config`` with docs and annotations.
  10. >>> class MyConfig(Config):
  11. ... '''Breakfast!'''
  12. ...
  13. ... eggs: int
  14. ... spam: int
  15. ...
  16. ... def _on_setattr(self, key, value):
  17. ... assert isinstance(value, int) and value >= 0
  18. ... return value
  19. >>> cfg = MyConfig(eggs=1, spam=5)
  20. Another way is to simply pass the initial configuration as keyword arguments to
  21. the ``Config`` instance:
  22. >>> cfg1 = Config(eggs=1, spam=5)
  23. >>> cfg1
  24. Config(eggs=1, spam=5)
  25. Once defined, config items may be modified, but can't be added or deleted by default.
  26. ``Config`` is a ``Mapping``, and can get and set configs via attributes or brackets:
  27. >>> cfg.eggs = 2
  28. >>> cfg.eggs
  29. 2
  30. >>> cfg["spam"] = 42
  31. >>> cfg["spam"]
  32. 42
  33. For convenience, it can also set configs within a context with the "with" statement:
  34. >>> with cfg(spam=3):
  35. ... print("spam (in context):", cfg.spam)
  36. spam (in context): 3
  37. >>> print("spam (after context):", cfg.spam)
  38. spam (after context): 42
  39. Subclasses may also define ``_on_setattr`` (as done in the example above)
  40. to ensure the value being assigned is valid:
  41. >>> cfg.spam = -1
  42. Traceback (most recent call last):
  43. ...
  44. AssertionError
  45. If a more flexible configuration object is needed that allows adding and deleting
  46. configurations, then pass ``strict=False`` when defining the subclass:
  47. >>> class FlexibleConfig(Config, strict=False):
  48. ... default_greeting: str = "Hello"
  49. >>> flexcfg = FlexibleConfig()
  50. >>> flexcfg.name = "Mr. Anderson"
  51. >>> flexcfg
  52. FlexibleConfig(default_greeting='Hello', name='Mr. Anderson')
  53. """
  54. def __init_subclass__(cls, strict=True):
  55. cls._strict = strict
  56. def __new__(cls, **kwargs):
  57. orig_class = cls
  58. if cls is Config:
  59. # Enable the "simple" case of accepting config definition as keywords
  60. cls = type(
  61. cls.__name__,
  62. (cls,),
  63. {"__annotations__": {key: typing.Any for key in kwargs}},
  64. )
  65. cls = dataclass(
  66. eq=False,
  67. repr=cls._strict,
  68. slots=cls._strict,
  69. kw_only=True,
  70. match_args=False,
  71. )(cls)
  72. if not cls._strict:
  73. cls.__repr__ = _flexible_repr
  74. cls._orig_class = orig_class # Save original class so we can pickle
  75. cls._prev = None # Stage previous configs to enable use as context manager
  76. cls._context_stack = [] # Stack of previous configs when used as context
  77. instance = object.__new__(cls)
  78. instance.__init__(**kwargs)
  79. return instance
  80. def _on_setattr(self, key, value):
  81. """Process config value and check whether it is valid. Useful for subclasses."""
  82. return value
  83. def _on_delattr(self, key):
  84. """Callback for when a config item is being deleted. Useful for subclasses."""
  85. # Control behavior of attributes
  86. def __dir__(self):
  87. return self.__dataclass_fields__.keys()
  88. def __setattr__(self, key, value):
  89. if self._strict and key not in self.__dataclass_fields__:
  90. raise AttributeError(f"Invalid config name: {key!r}")
  91. value = self._on_setattr(key, value)
  92. object.__setattr__(self, key, value)
  93. self.__class__._prev = None
  94. def __delattr__(self, key):
  95. if self._strict:
  96. raise TypeError(
  97. f"Configuration items can't be deleted (can't delete {key!r})."
  98. )
  99. self._on_delattr(key)
  100. object.__delattr__(self, key)
  101. self.__class__._prev = None
  102. # Be a `collection.abc.Collection`
  103. def __contains__(self, key):
  104. return (
  105. key in self.__dataclass_fields__ if self._strict else key in self.__dict__
  106. )
  107. def __iter__(self):
  108. return iter(self.__dataclass_fields__ if self._strict else self.__dict__)
  109. def __len__(self):
  110. return len(self.__dataclass_fields__ if self._strict else self.__dict__)
  111. def __reversed__(self):
  112. return reversed(self.__dataclass_fields__ if self._strict else self.__dict__)
  113. # Add dunder methods for `collections.abc.Mapping`
  114. def __getitem__(self, key):
  115. try:
  116. return getattr(self, key)
  117. except AttributeError as err:
  118. raise KeyError(*err.args) from None
  119. def __setitem__(self, key, value):
  120. try:
  121. self.__setattr__(key, value)
  122. except AttributeError as err:
  123. raise KeyError(*err.args) from None
  124. def __delitem__(self, key):
  125. try:
  126. self.__delattr__(key)
  127. except AttributeError as err:
  128. raise KeyError(*err.args) from None
  129. _ipython_key_completions_ = __dir__ # config["<TAB>
  130. # Go ahead and make it a `collections.abc.Mapping`
  131. def get(self, key, default=None):
  132. return getattr(self, key, default)
  133. def items(self):
  134. return collections.abc.ItemsView(self)
  135. def keys(self):
  136. return collections.abc.KeysView(self)
  137. def values(self):
  138. return collections.abc.ValuesView(self)
  139. # dataclass can define __eq__ for us, but do it here so it works after pickling
  140. def __eq__(self, other):
  141. if not isinstance(other, Config):
  142. return NotImplemented
  143. return self._orig_class == other._orig_class and self.items() == other.items()
  144. # Make pickle work
  145. def __reduce__(self):
  146. return self._deserialize, (self._orig_class, dict(self))
  147. @staticmethod
  148. def _deserialize(cls, kwargs):
  149. return cls(**kwargs)
  150. # Allow to be used as context manager
  151. def __call__(self, **kwargs):
  152. kwargs = {key: self._on_setattr(key, val) for key, val in kwargs.items()}
  153. prev = dict(self)
  154. for key, val in kwargs.items():
  155. setattr(self, key, val)
  156. self.__class__._prev = prev
  157. return self
  158. def __enter__(self):
  159. if self.__class__._prev is None:
  160. raise RuntimeError(
  161. "Config being used as a context manager without config items being set. "
  162. "Set config items via keyword arguments when calling the config object. "
  163. "For example, using config as a context manager should be like:\n\n"
  164. ' >>> with cfg(breakfast="spam"):\n'
  165. " ... ... # Do stuff\n"
  166. )
  167. self.__class__._context_stack.append(self.__class__._prev)
  168. self.__class__._prev = None
  169. return self
  170. def __exit__(self, exc_type, exc_value, traceback):
  171. prev = self.__class__._context_stack.pop()
  172. for key, val in prev.items():
  173. setattr(self, key, val)
  174. def _flexible_repr(self):
  175. return (
  176. f"{self.__class__.__qualname__}("
  177. + ", ".join(f"{key}={val!r}" for key, val in self.__dict__.items())
  178. + ")"
  179. )
  180. # Register, b/c `Mapping.__subclasshook__` returns `NotImplemented`
  181. collections.abc.Mapping.register(Config)
  182. class BackendPriorities(Config, strict=False):
  183. """Configuration to control automatic conversion to and calling of backends.
  184. Priority is given to backends listed earlier.
  185. Parameters
  186. ----------
  187. algos : list of backend names
  188. This controls "algorithms" such as ``nx.pagerank`` that don't return a graph.
  189. generators : list of backend names
  190. This controls "generators" such as ``nx.from_pandas_edgelist`` that return a graph.
  191. classes : list of backend names
  192. This controls graph classes such as ``nx.Graph()``.
  193. kwargs : variadic keyword arguments of function name to list of backend names
  194. This allows each function to be configured separately and will override the config
  195. in ``algos`` or ``generators`` if present. The dispatchable function name may be
  196. gotten from the ``.name`` attribute such as ``nx.pagerank.name`` (it's typically
  197. the same as the name of the function).
  198. """
  199. algos: list[str]
  200. generators: list[str]
  201. classes: list[str]
  202. def _on_setattr(self, key, value):
  203. from .backends import _registered_algorithms, backend_info
  204. if key in {"algos", "generators", "classes"}:
  205. pass
  206. elif key not in _registered_algorithms:
  207. raise AttributeError(
  208. f"Invalid config name: {key!r}. Expected 'algos', 'generators', "
  209. "'classes', or a name of a dispatchable function "
  210. "(e.g. `.name` attribute of the function)."
  211. )
  212. if not (isinstance(value, list) and all(isinstance(x, str) for x in value)):
  213. raise TypeError(
  214. f"{key!r} config must be a list of backend names; got {value!r}"
  215. )
  216. if missing := {x for x in value if x not in backend_info}:
  217. missing = ", ".join(map(repr, sorted(missing)))
  218. raise ValueError(f"Unknown backend when setting {key!r}: {missing}")
  219. return value
  220. def _on_delattr(self, key):
  221. if key in {"algos", "generators", "classes"}:
  222. raise TypeError(f"{key!r} configuration item can't be deleted.")
  223. class NetworkXConfig(Config):
  224. """Configuration for NetworkX that controls behaviors such as how to use backends.
  225. Attribute and bracket notation are supported for getting and setting configurations::
  226. >>> nx.config.backend_priority == nx.config["backend_priority"]
  227. True
  228. Parameters
  229. ----------
  230. backend_priority : list of backend names or dict or BackendPriorities
  231. Enable automatic conversion of graphs to backend graphs for functions
  232. implemented by the backend. Priority is given to backends listed earlier.
  233. This is a nested configuration with keys ``algos``, ``generators``,
  234. ``classes``, and, optionally, function names. Setting this value to a
  235. list of backend names will set ``nx.config.backend_priority.algos``.
  236. For more information, see ``help(nx.config.backend_priority)``.
  237. Default is empty list.
  238. backends : Config mapping of backend names to backend Config
  239. The keys of the Config mapping are names of all installed NetworkX backends,
  240. and the values are their configurations as Config mappings.
  241. cache_converted_graphs : bool
  242. If True, then save converted graphs to the cache of the input graph. Graph
  243. conversion may occur when automatically using a backend from `backend_priority`
  244. or when using the `backend=` keyword argument to a function call. Caching can
  245. improve performance by avoiding repeated conversions, but it uses more memory.
  246. Care should be taken to not manually mutate a graph that has cached graphs; for
  247. example, ``G[u][v][k] = val`` changes the graph, but does not clear the cache.
  248. Using methods such as ``G.add_edge(u, v, weight=val)`` will clear the cache to
  249. keep it consistent. ``G.__networkx_cache__.clear()`` manually clears the cache.
  250. Default is True.
  251. fallback_to_nx : bool
  252. If True, then "fall back" and run with the default "networkx" implementation
  253. for dispatchable functions not implemented by backends of input graphs. When a
  254. backend graph is passed to a dispatchable function, the default behavior is to
  255. use the implementation from that backend if possible and raise if not. Enabling
  256. ``fallback_to_nx`` makes the networkx implementation the fallback to use instead
  257. of raising, and will convert the backend graph to a networkx-compatible graph.
  258. Default is False.
  259. warnings_to_ignore : set of strings
  260. Control which warnings from NetworkX are not emitted. Valid elements:
  261. - `"cache"`: when a cached value is used from ``G.__networkx_cache__``.
  262. Notes
  263. -----
  264. Environment variables may be used to control some default configurations:
  265. - ``NETWORKX_BACKEND_PRIORITY``: set ``backend_priority.algos`` from comma-separated names.
  266. - ``NETWORKX_CACHE_CONVERTED_GRAPHS``: set ``cache_converted_graphs`` to True if nonempty.
  267. - ``NETWORKX_FALLBACK_TO_NX``: set ``fallback_to_nx`` to True if nonempty.
  268. - ``NETWORKX_WARNINGS_TO_IGNORE``: set `warnings_to_ignore` from comma-separated names.
  269. and can be used for finer control of ``backend_priority`` such as:
  270. - ``NETWORKX_BACKEND_PRIORITY_ALGOS``: same as ``NETWORKX_BACKEND_PRIORITY``
  271. to set ``backend_priority.algos``.
  272. This is a global configuration. Use with caution when using from multiple threads.
  273. """
  274. backend_priority: BackendPriorities
  275. backends: Config
  276. cache_converted_graphs: bool
  277. fallback_to_nx: bool
  278. warnings_to_ignore: set[str]
  279. def _on_setattr(self, key, value):
  280. from .backends import backend_info
  281. if key == "backend_priority":
  282. if isinstance(value, list):
  283. # `config.backend_priority = [backend]` sets `backend_priority.algos`
  284. value = BackendPriorities(
  285. **dict(
  286. self.backend_priority,
  287. algos=self.backend_priority._on_setattr("algos", value),
  288. )
  289. )
  290. elif isinstance(value, dict):
  291. kwargs = value
  292. value = BackendPriorities(algos=[], generators=[], classes=[])
  293. for key, val in kwargs.items():
  294. setattr(value, key, val)
  295. elif not isinstance(value, BackendPriorities):
  296. raise TypeError(
  297. f"{key!r} config must be a dict of lists of backend names; got {value!r}"
  298. )
  299. elif key == "backends":
  300. if not (
  301. isinstance(value, Config)
  302. and all(isinstance(key, str) for key in value)
  303. and all(isinstance(val, Config) for val in value.values())
  304. ):
  305. raise TypeError(
  306. f"{key!r} config must be a Config of backend configs; got {value!r}"
  307. )
  308. if missing := {x for x in value if x not in backend_info}:
  309. missing = ", ".join(map(repr, sorted(missing)))
  310. raise ValueError(f"Unknown backend when setting {key!r}: {missing}")
  311. elif key in {"cache_converted_graphs", "fallback_to_nx"}:
  312. if not isinstance(value, bool):
  313. raise TypeError(f"{key!r} config must be True or False; got {value!r}")
  314. elif key == "warnings_to_ignore":
  315. if not (isinstance(value, set) and all(isinstance(x, str) for x in value)):
  316. raise TypeError(
  317. f"{key!r} config must be a set of warning names; got {value!r}"
  318. )
  319. known_warnings = {"cache"}
  320. if missing := {x for x in value if x not in known_warnings}:
  321. missing = ", ".join(map(repr, sorted(missing)))
  322. raise ValueError(
  323. f"Unknown warning when setting {key!r}: {missing}. Valid entries: "
  324. + ", ".join(sorted(known_warnings))
  325. )
  326. return value