_funcs.py 14 KB

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