_funcs.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. # SPDX-License-Identifier: MIT
  2. import copy
  3. from ._compat import PY_3_9_PLUS, get_generic_base
  4. from ._make import NOTHING, _obj_setattr, fields
  5. from .exceptions import AttrsAttributeNotFoundError
  6. def asdict(
  7. inst,
  8. recurse=True,
  9. filter=None,
  10. dict_factory=dict,
  11. retain_collection_types=False,
  12. value_serializer=None,
  13. ):
  14. """
  15. Return the *attrs* attribute values of *inst* as a dict.
  16. Optionally recurse into other *attrs*-decorated classes.
  17. :param inst: Instance of an *attrs*-decorated class.
  18. :param bool recurse: Recurse into classes that are also
  19. *attrs*-decorated.
  20. :param callable filter: A callable whose return code determines whether an
  21. attribute or element is included (``True``) or dropped (``False``). Is
  22. called with the `attrs.Attribute` as the first argument and the
  23. value as the second argument.
  24. :param callable dict_factory: A callable to produce dictionaries from. For
  25. example, to produce ordered dictionaries instead of normal Python
  26. dictionaries, pass in ``collections.OrderedDict``.
  27. :param bool retain_collection_types: Do not convert to ``list`` when
  28. encountering an attribute whose type is ``tuple`` or ``set``. Only
  29. meaningful if ``recurse`` is ``True``.
  30. :param Optional[callable] value_serializer: A hook that is called for every
  31. attribute or dict key/value. It receives the current instance, field
  32. and value and must return the (updated) value. The hook is run *after*
  33. the optional *filter* has been applied.
  34. :rtype: return type of *dict_factory*
  35. :raise attrs.exceptions.NotAnAttrsClassError: If *cls* is not an *attrs*
  36. class.
  37. .. versionadded:: 16.0.0 *dict_factory*
  38. .. versionadded:: 16.1.0 *retain_collection_types*
  39. .. versionadded:: 20.3.0 *value_serializer*
  40. .. versionadded:: 21.3.0 If a dict has a collection for a key, it is
  41. serialized as a tuple.
  42. """
  43. attrs = fields(inst.__class__)
  44. rv = dict_factory()
  45. for a in attrs:
  46. v = getattr(inst, a.name)
  47. if filter is not None and not filter(a, v):
  48. continue
  49. if value_serializer is not None:
  50. v = value_serializer(inst, a, v)
  51. if recurse is True:
  52. if has(v.__class__):
  53. rv[a.name] = asdict(
  54. v,
  55. recurse=True,
  56. filter=filter,
  57. dict_factory=dict_factory,
  58. retain_collection_types=retain_collection_types,
  59. value_serializer=value_serializer,
  60. )
  61. elif isinstance(v, (tuple, list, set, frozenset)):
  62. cf = v.__class__ if retain_collection_types is True else list
  63. items = [
  64. _asdict_anything(
  65. i,
  66. is_key=False,
  67. filter=filter,
  68. dict_factory=dict_factory,
  69. retain_collection_types=retain_collection_types,
  70. value_serializer=value_serializer,
  71. )
  72. for i in v
  73. ]
  74. try:
  75. rv[a.name] = cf(items)
  76. except TypeError:
  77. if not issubclass(cf, tuple):
  78. raise
  79. # Workaround for TypeError: cf.__new__() missing 1 required
  80. # positional argument (which appears, for a namedturle)
  81. rv[a.name] = cf(*items)
  82. elif isinstance(v, dict):
  83. df = dict_factory
  84. rv[a.name] = df(
  85. (
  86. _asdict_anything(
  87. kk,
  88. is_key=True,
  89. filter=filter,
  90. dict_factory=df,
  91. retain_collection_types=retain_collection_types,
  92. value_serializer=value_serializer,
  93. ),
  94. _asdict_anything(
  95. vv,
  96. is_key=False,
  97. filter=filter,
  98. dict_factory=df,
  99. retain_collection_types=retain_collection_types,
  100. value_serializer=value_serializer,
  101. ),
  102. )
  103. for kk, vv in v.items()
  104. )
  105. else:
  106. rv[a.name] = v
  107. else:
  108. rv[a.name] = v
  109. return rv
  110. def _asdict_anything(
  111. val,
  112. is_key,
  113. filter,
  114. dict_factory,
  115. retain_collection_types,
  116. value_serializer,
  117. ):
  118. """
  119. ``asdict`` only works on attrs instances, this works on anything.
  120. """
  121. if getattr(val.__class__, "__attrs_attrs__", None) is not None:
  122. # Attrs class.
  123. rv = asdict(
  124. val,
  125. recurse=True,
  126. filter=filter,
  127. dict_factory=dict_factory,
  128. retain_collection_types=retain_collection_types,
  129. value_serializer=value_serializer,
  130. )
  131. elif isinstance(val, (tuple, list, set, frozenset)):
  132. if retain_collection_types is True:
  133. cf = val.__class__
  134. elif is_key:
  135. cf = tuple
  136. else:
  137. cf = list
  138. rv = cf(
  139. [
  140. _asdict_anything(
  141. i,
  142. is_key=False,
  143. filter=filter,
  144. dict_factory=dict_factory,
  145. retain_collection_types=retain_collection_types,
  146. value_serializer=value_serializer,
  147. )
  148. for i in val
  149. ]
  150. )
  151. elif isinstance(val, dict):
  152. df = dict_factory
  153. rv = df(
  154. (
  155. _asdict_anything(
  156. kk,
  157. is_key=True,
  158. filter=filter,
  159. dict_factory=df,
  160. retain_collection_types=retain_collection_types,
  161. value_serializer=value_serializer,
  162. ),
  163. _asdict_anything(
  164. vv,
  165. is_key=False,
  166. filter=filter,
  167. dict_factory=df,
  168. retain_collection_types=retain_collection_types,
  169. value_serializer=value_serializer,
  170. ),
  171. )
  172. for kk, vv in val.items()
  173. )
  174. else:
  175. rv = val
  176. if value_serializer is not None:
  177. rv = value_serializer(None, None, rv)
  178. return rv
  179. def astuple(
  180. inst,
  181. recurse=True,
  182. filter=None,
  183. tuple_factory=tuple,
  184. retain_collection_types=False,
  185. ):
  186. """
  187. Return the *attrs* attribute values of *inst* as a tuple.
  188. Optionally recurse into other *attrs*-decorated classes.
  189. :param inst: Instance of an *attrs*-decorated class.
  190. :param bool recurse: Recurse into classes that are also
  191. *attrs*-decorated.
  192. :param callable filter: A callable whose return code determines whether an
  193. attribute or element is included (``True``) or dropped (``False``). Is
  194. called with the `attrs.Attribute` as the first argument and the
  195. value as the second argument.
  196. :param callable tuple_factory: A callable to produce tuples from. For
  197. example, to produce lists instead of tuples.
  198. :param bool retain_collection_types: Do not convert to ``list``
  199. or ``dict`` when encountering an attribute which type is
  200. ``tuple``, ``dict`` or ``set``. Only meaningful if ``recurse`` is
  201. ``True``.
  202. :rtype: return type of *tuple_factory*
  203. :raise attrs.exceptions.NotAnAttrsClassError: If *cls* is not an *attrs*
  204. class.
  205. .. versionadded:: 16.2.0
  206. """
  207. attrs = fields(inst.__class__)
  208. rv = []
  209. retain = retain_collection_types # Very long. :/
  210. for a in attrs:
  211. v = getattr(inst, a.name)
  212. if filter is not None and not filter(a, v):
  213. continue
  214. if recurse is True:
  215. if has(v.__class__):
  216. rv.append(
  217. astuple(
  218. v,
  219. recurse=True,
  220. filter=filter,
  221. tuple_factory=tuple_factory,
  222. retain_collection_types=retain,
  223. )
  224. )
  225. elif isinstance(v, (tuple, list, set, frozenset)):
  226. cf = v.__class__ if retain is True else list
  227. items = [
  228. astuple(
  229. j,
  230. recurse=True,
  231. filter=filter,
  232. tuple_factory=tuple_factory,
  233. retain_collection_types=retain,
  234. )
  235. if has(j.__class__)
  236. else j
  237. for j in v
  238. ]
  239. try:
  240. rv.append(cf(items))
  241. except TypeError:
  242. if not issubclass(cf, tuple):
  243. raise
  244. # Workaround for TypeError: cf.__new__() missing 1 required
  245. # positional argument (which appears, for a namedturle)
  246. rv.append(cf(*items))
  247. elif isinstance(v, dict):
  248. df = v.__class__ if retain is True else dict
  249. rv.append(
  250. df(
  251. (
  252. astuple(
  253. kk,
  254. tuple_factory=tuple_factory,
  255. retain_collection_types=retain,
  256. )
  257. if has(kk.__class__)
  258. else kk,
  259. astuple(
  260. vv,
  261. tuple_factory=tuple_factory,
  262. retain_collection_types=retain,
  263. )
  264. if has(vv.__class__)
  265. else vv,
  266. )
  267. for kk, vv in v.items()
  268. )
  269. )
  270. else:
  271. rv.append(v)
  272. else:
  273. rv.append(v)
  274. return rv if tuple_factory is list else tuple_factory(rv)
  275. def has(cls):
  276. """
  277. Check whether *cls* is a class with *attrs* attributes.
  278. :param type cls: Class to introspect.
  279. :raise TypeError: If *cls* is not a class.
  280. :rtype: bool
  281. """
  282. attrs = getattr(cls, "__attrs_attrs__", None)
  283. if attrs is not None:
  284. return True
  285. # No attrs, maybe it's a specialized generic (A[str])?
  286. generic_base = get_generic_base(cls)
  287. if generic_base is not None:
  288. generic_attrs = getattr(generic_base, "__attrs_attrs__", None)
  289. if generic_attrs is not None:
  290. # Stick it on here for speed next time.
  291. cls.__attrs_attrs__ = generic_attrs
  292. return generic_attrs is not None
  293. return False
  294. def assoc(inst, **changes):
  295. """
  296. Copy *inst* and apply *changes*.
  297. This is different from `evolve` that applies the changes to the arguments
  298. that create the new instance.
  299. `evolve`'s behavior is preferable, but there are `edge cases`_ where it
  300. doesn't work. Therefore `assoc` is deprecated, but will not be removed.
  301. .. _`edge cases`: https://github.com/python-attrs/attrs/issues/251
  302. :param inst: Instance of a class with *attrs* attributes.
  303. :param changes: Keyword changes in the new copy.
  304. :return: A copy of inst with *changes* incorporated.
  305. :raise attrs.exceptions.AttrsAttributeNotFoundError: If *attr_name*
  306. couldn't be found on *cls*.
  307. :raise attrs.exceptions.NotAnAttrsClassError: If *cls* is not an *attrs*
  308. class.
  309. .. deprecated:: 17.1.0
  310. Use `attrs.evolve` instead if you can.
  311. This function will not be removed du to the slightly different approach
  312. compared to `attrs.evolve`.
  313. """
  314. new = copy.copy(inst)
  315. attrs = fields(inst.__class__)
  316. for k, v in changes.items():
  317. a = getattr(attrs, k, NOTHING)
  318. if a is NOTHING:
  319. msg = f"{k} is not an attrs attribute on {new.__class__}."
  320. raise AttrsAttributeNotFoundError(msg)
  321. _obj_setattr(new, k, v)
  322. return new
  323. def evolve(*args, **changes):
  324. """
  325. Create a new instance, based on the first positional argument with
  326. *changes* applied.
  327. :param inst: Instance of a class with *attrs* attributes.
  328. :param changes: Keyword changes in the new copy.
  329. :return: A copy of inst with *changes* incorporated.
  330. :raise TypeError: If *attr_name* couldn't be found in the class
  331. ``__init__``.
  332. :raise attrs.exceptions.NotAnAttrsClassError: If *cls* is not an *attrs*
  333. class.
  334. .. versionadded:: 17.1.0
  335. .. deprecated:: 23.1.0
  336. It is now deprecated to pass the instance using the keyword argument
  337. *inst*. It will raise a warning until at least April 2024, after which
  338. it will become an error. Always pass the instance as a positional
  339. argument.
  340. """
  341. # Try to get instance by positional argument first.
  342. # Use changes otherwise and warn it'll break.
  343. if args:
  344. try:
  345. (inst,) = args
  346. except ValueError:
  347. msg = f"evolve() takes 1 positional argument, but {len(args)} were given"
  348. raise TypeError(msg) from None
  349. else:
  350. try:
  351. inst = changes.pop("inst")
  352. except KeyError:
  353. msg = "evolve() missing 1 required positional argument: 'inst'"
  354. raise TypeError(msg) from None
  355. import warnings
  356. warnings.warn(
  357. "Passing the instance per keyword argument is deprecated and "
  358. "will stop working in, or after, April 2024.",
  359. DeprecationWarning,
  360. stacklevel=2,
  361. )
  362. cls = inst.__class__
  363. attrs = fields(cls)
  364. for a in attrs:
  365. if not a.init:
  366. continue
  367. attr_name = a.name # To deal with private attributes.
  368. init_name = a.alias
  369. if init_name not in changes:
  370. changes[init_name] = getattr(inst, attr_name)
  371. return cls(**changes)
  372. def resolve_types(
  373. cls, globalns=None, localns=None, attribs=None, include_extras=True
  374. ):
  375. """
  376. Resolve any strings and forward annotations in type annotations.
  377. This is only required if you need concrete types in `Attribute`'s *type*
  378. field. In other words, you don't need to resolve your types if you only
  379. use them for static type checking.
  380. With no arguments, names will be looked up in the module in which the class
  381. was created. If this is not what you want, e.g. if the name only exists
  382. inside a method, you may pass *globalns* or *localns* to specify other
  383. dictionaries in which to look up these names. See the docs of
  384. `typing.get_type_hints` for more details.
  385. :param type cls: Class to resolve.
  386. :param Optional[dict] globalns: Dictionary containing global variables.
  387. :param Optional[dict] localns: Dictionary containing local variables.
  388. :param Optional[list] attribs: List of attribs for the given class.
  389. This is necessary when calling from inside a ``field_transformer``
  390. since *cls* is not an *attrs* class yet.
  391. :param bool include_extras: Resolve more accurately, if possible.
  392. Pass ``include_extras`` to ``typing.get_hints``, if supported by the
  393. typing module. On supported Python versions (3.9+), this resolves the
  394. types more accurately.
  395. :raise TypeError: If *cls* is not a class.
  396. :raise attrs.exceptions.NotAnAttrsClassError: If *cls* is not an *attrs*
  397. class and you didn't pass any attribs.
  398. :raise NameError: If types cannot be resolved because of missing variables.
  399. :returns: *cls* so you can use this function also as a class decorator.
  400. Please note that you have to apply it **after** `attrs.define`. That
  401. means the decorator has to come in the line **before** `attrs.define`.
  402. .. versionadded:: 20.1.0
  403. .. versionadded:: 21.1.0 *attribs*
  404. .. versionadded:: 23.1.0 *include_extras*
  405. """
  406. # Since calling get_type_hints is expensive we cache whether we've
  407. # done it already.
  408. if getattr(cls, "__attrs_types_resolved__", None) != cls:
  409. import typing
  410. kwargs = {"globalns": globalns, "localns": localns}
  411. if PY_3_9_PLUS:
  412. kwargs["include_extras"] = include_extras
  413. hints = typing.get_type_hints(cls, **kwargs)
  414. for field in fields(cls) if attribs is None else attribs:
  415. if field.name in hints:
  416. # Since fields have been frozen we must work around it.
  417. _obj_setattr(field, "type", hints[field.name])
  418. # We store the class we resolved so that subclasses know they haven't
  419. # been resolved.
  420. cls.__attrs_types_resolved__ = cls
  421. # Return the class so you can use it as a decorator too.
  422. return cls