_funcs.py 13 KB

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