Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_funcs.py 16KB

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