logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

dataclasses.py (55882B)


  1. import re
  2. import sys
  3. import copy
  4. import types
  5. import inspect
  6. import keyword
  7. import builtins
  8. import functools
  9. import abc
  10. import _thread
  11. from types import FunctionType, GenericAlias
  12. __all__ = ['dataclass',
  13. 'field',
  14. 'Field',
  15. 'FrozenInstanceError',
  16. 'InitVar',
  17. 'KW_ONLY',
  18. 'MISSING',
  19. # Helper functions.
  20. 'fields',
  21. 'asdict',
  22. 'astuple',
  23. 'make_dataclass',
  24. 'replace',
  25. 'is_dataclass',
  26. ]
  27. # Conditions for adding methods. The boxes indicate what action the
  28. # dataclass decorator takes. For all of these tables, when I talk
  29. # about init=, repr=, eq=, order=, unsafe_hash=, or frozen=, I'm
  30. # referring to the arguments to the @dataclass decorator. When
  31. # checking if a dunder method already exists, I mean check for an
  32. # entry in the class's __dict__. I never check to see if an attribute
  33. # is defined in a base class.
  34. # Key:
  35. # +=========+=========================================+
  36. # + Value | Meaning |
  37. # +=========+=========================================+
  38. # | <blank> | No action: no method is added. |
  39. # +---------+-----------------------------------------+
  40. # | add | Generated method is added. |
  41. # +---------+-----------------------------------------+
  42. # | raise | TypeError is raised. |
  43. # +---------+-----------------------------------------+
  44. # | None | Attribute is set to None. |
  45. # +=========+=========================================+
  46. # __init__
  47. #
  48. # +--- init= parameter
  49. # |
  50. # v | | |
  51. # | no | yes | <--- class has __init__ in __dict__?
  52. # +=======+=======+=======+
  53. # | False | | |
  54. # +-------+-------+-------+
  55. # | True | add | | <- the default
  56. # +=======+=======+=======+
  57. # __repr__
  58. #
  59. # +--- repr= parameter
  60. # |
  61. # v | | |
  62. # | no | yes | <--- class has __repr__ in __dict__?
  63. # +=======+=======+=======+
  64. # | False | | |
  65. # +-------+-------+-------+
  66. # | True | add | | <- the default
  67. # +=======+=======+=======+
  68. # __setattr__
  69. # __delattr__
  70. #
  71. # +--- frozen= parameter
  72. # |
  73. # v | | |
  74. # | no | yes | <--- class has __setattr__ or __delattr__ in __dict__?
  75. # +=======+=======+=======+
  76. # | False | | | <- the default
  77. # +-------+-------+-------+
  78. # | True | add | raise |
  79. # +=======+=======+=======+
  80. # Raise because not adding these methods would break the "frozen-ness"
  81. # of the class.
  82. # __eq__
  83. #
  84. # +--- eq= parameter
  85. # |
  86. # v | | |
  87. # | no | yes | <--- class has __eq__ in __dict__?
  88. # +=======+=======+=======+
  89. # | False | | |
  90. # +-------+-------+-------+
  91. # | True | add | | <- the default
  92. # +=======+=======+=======+
  93. # __lt__
  94. # __le__
  95. # __gt__
  96. # __ge__
  97. #
  98. # +--- order= parameter
  99. # |
  100. # v | | |
  101. # | no | yes | <--- class has any comparison method in __dict__?
  102. # +=======+=======+=======+
  103. # | False | | | <- the default
  104. # +-------+-------+-------+
  105. # | True | add | raise |
  106. # +=======+=======+=======+
  107. # Raise because to allow this case would interfere with using
  108. # functools.total_ordering.
  109. # __hash__
  110. # +------------------- unsafe_hash= parameter
  111. # | +----------- eq= parameter
  112. # | | +--- frozen= parameter
  113. # | | |
  114. # v v v | | |
  115. # | no | yes | <--- class has explicitly defined __hash__
  116. # +=======+=======+=======+========+========+
  117. # | False | False | False | | | No __eq__, use the base class __hash__
  118. # +-------+-------+-------+--------+--------+
  119. # | False | False | True | | | No __eq__, use the base class __hash__
  120. # +-------+-------+-------+--------+--------+
  121. # | False | True | False | None | | <-- the default, not hashable
  122. # +-------+-------+-------+--------+--------+
  123. # | False | True | True | add | | Frozen, so hashable, allows override
  124. # +-------+-------+-------+--------+--------+
  125. # | True | False | False | add | raise | Has no __eq__, but hashable
  126. # +-------+-------+-------+--------+--------+
  127. # | True | False | True | add | raise | Has no __eq__, but hashable
  128. # +-------+-------+-------+--------+--------+
  129. # | True | True | False | add | raise | Not frozen, but hashable
  130. # +-------+-------+-------+--------+--------+
  131. # | True | True | True | add | raise | Frozen, so hashable
  132. # +=======+=======+=======+========+========+
  133. # For boxes that are blank, __hash__ is untouched and therefore
  134. # inherited from the base class. If the base is object, then
  135. # id-based hashing is used.
  136. #
  137. # Note that a class may already have __hash__=None if it specified an
  138. # __eq__ method in the class body (not one that was created by
  139. # @dataclass).
  140. #
  141. # See _hash_action (below) for a coded version of this table.
  142. # __match_args__
  143. #
  144. # +--- match_args= parameter
  145. # |
  146. # v | | |
  147. # | no | yes | <--- class has __match_args__ in __dict__?
  148. # +=======+=======+=======+
  149. # | False | | |
  150. # +-------+-------+-------+
  151. # | True | add | | <- the default
  152. # +=======+=======+=======+
  153. # __match_args__ is always added unless the class already defines it. It is a
  154. # tuple of __init__ parameter names; non-init fields must be matched by keyword.
  155. # Raised when an attempt is made to modify a frozen class.
  156. class FrozenInstanceError(AttributeError): pass
  157. # A sentinel object for default values to signal that a default
  158. # factory will be used. This is given a nice repr() which will appear
  159. # in the function signature of dataclasses' constructors.
  160. class _HAS_DEFAULT_FACTORY_CLASS:
  161. def __repr__(self):
  162. return '<factory>'
  163. _HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS()
  164. # A sentinel object to detect if a parameter is supplied or not. Use
  165. # a class to give it a better repr.
  166. class _MISSING_TYPE:
  167. pass
  168. MISSING = _MISSING_TYPE()
  169. # A sentinel object to indicate that following fields are keyword-only by
  170. # default. Use a class to give it a better repr.
  171. class _KW_ONLY_TYPE:
  172. pass
  173. KW_ONLY = _KW_ONLY_TYPE()
  174. # Since most per-field metadata will be unused, create an empty
  175. # read-only proxy that can be shared among all fields.
  176. _EMPTY_METADATA = types.MappingProxyType({})
  177. # Markers for the various kinds of fields and pseudo-fields.
  178. class _FIELD_BASE:
  179. def __init__(self, name):
  180. self.name = name
  181. def __repr__(self):
  182. return self.name
  183. _FIELD = _FIELD_BASE('_FIELD')
  184. _FIELD_CLASSVAR = _FIELD_BASE('_FIELD_CLASSVAR')
  185. _FIELD_INITVAR = _FIELD_BASE('_FIELD_INITVAR')
  186. # The name of an attribute on the class where we store the Field
  187. # objects. Also used to check if a class is a Data Class.
  188. _FIELDS = '__dataclass_fields__'
  189. # The name of an attribute on the class that stores the parameters to
  190. # @dataclass.
  191. _PARAMS = '__dataclass_params__'
  192. # The name of the function, that if it exists, is called at the end of
  193. # __init__.
  194. _POST_INIT_NAME = '__post_init__'
  195. # String regex that string annotations for ClassVar or InitVar must match.
  196. # Allows "identifier.identifier[" or "identifier[".
  197. # https://bugs.python.org/issue33453 for details.
  198. _MODULE_IDENTIFIER_RE = re.compile(r'^(?:\s*(\w+)\s*\.)?\s*(\w+)')
  199. class InitVar:
  200. __slots__ = ('type', )
  201. def __init__(self, type):
  202. self.type = type
  203. def __repr__(self):
  204. if isinstance(self.type, type):
  205. type_name = self.type.__name__
  206. else:
  207. # typing objects, e.g. List[int]
  208. type_name = repr(self.type)
  209. return f'dataclasses.InitVar[{type_name}]'
  210. def __class_getitem__(cls, type):
  211. return InitVar(type)
  212. # Instances of Field are only ever created from within this module,
  213. # and only from the field() function, although Field instances are
  214. # exposed externally as (conceptually) read-only objects.
  215. #
  216. # name and type are filled in after the fact, not in __init__.
  217. # They're not known at the time this class is instantiated, but it's
  218. # convenient if they're available later.
  219. #
  220. # When cls._FIELDS is filled in with a list of Field objects, the name
  221. # and type fields will have been populated.
  222. class Field:
  223. __slots__ = ('name',
  224. 'type',
  225. 'default',
  226. 'default_factory',
  227. 'repr',
  228. 'hash',
  229. 'init',
  230. 'compare',
  231. 'metadata',
  232. 'kw_only',
  233. '_field_type', # Private: not to be used by user code.
  234. )
  235. def __init__(self, default, default_factory, init, repr, hash, compare,
  236. metadata, kw_only):
  237. self.name = None
  238. self.type = None
  239. self.default = default
  240. self.default_factory = default_factory
  241. self.init = init
  242. self.repr = repr
  243. self.hash = hash
  244. self.compare = compare
  245. self.metadata = (_EMPTY_METADATA
  246. if metadata is None else
  247. types.MappingProxyType(metadata))
  248. self.kw_only = kw_only
  249. self._field_type = None
  250. def __repr__(self):
  251. return ('Field('
  252. f'name={self.name!r},'
  253. f'type={self.type!r},'
  254. f'default={self.default!r},'
  255. f'default_factory={self.default_factory!r},'
  256. f'init={self.init!r},'
  257. f'repr={self.repr!r},'
  258. f'hash={self.hash!r},'
  259. f'compare={self.compare!r},'
  260. f'metadata={self.metadata!r},'
  261. f'kw_only={self.kw_only!r},'
  262. f'_field_type={self._field_type}'
  263. ')')
  264. # This is used to support the PEP 487 __set_name__ protocol in the
  265. # case where we're using a field that contains a descriptor as a
  266. # default value. For details on __set_name__, see
  267. # https://www.python.org/dev/peps/pep-0487/#implementation-details.
  268. #
  269. # Note that in _process_class, this Field object is overwritten
  270. # with the default value, so the end result is a descriptor that
  271. # had __set_name__ called on it at the right time.
  272. def __set_name__(self, owner, name):
  273. func = getattr(type(self.default), '__set_name__', None)
  274. if func:
  275. # There is a __set_name__ method on the descriptor, call
  276. # it.
  277. func(self.default, owner, name)
  278. __class_getitem__ = classmethod(GenericAlias)
  279. class _DataclassParams:
  280. __slots__ = ('init',
  281. 'repr',
  282. 'eq',
  283. 'order',
  284. 'unsafe_hash',
  285. 'frozen',
  286. )
  287. def __init__(self, init, repr, eq, order, unsafe_hash, frozen):
  288. self.init = init
  289. self.repr = repr
  290. self.eq = eq
  291. self.order = order
  292. self.unsafe_hash = unsafe_hash
  293. self.frozen = frozen
  294. def __repr__(self):
  295. return ('_DataclassParams('
  296. f'init={self.init!r},'
  297. f'repr={self.repr!r},'
  298. f'eq={self.eq!r},'
  299. f'order={self.order!r},'
  300. f'unsafe_hash={self.unsafe_hash!r},'
  301. f'frozen={self.frozen!r}'
  302. ')')
  303. # This function is used instead of exposing Field creation directly,
  304. # so that a type checker can be told (via overloads) that this is a
  305. # function whose type depends on its parameters.
  306. def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True,
  307. hash=None, compare=True, metadata=None, kw_only=MISSING):
  308. """Return an object to identify dataclass fields.
  309. default is the default value of the field. default_factory is a
  310. 0-argument function called to initialize a field's value. If init
  311. is true, the field will be a parameter to the class's __init__()
  312. function. If repr is true, the field will be included in the
  313. object's repr(). If hash is true, the field will be included in the
  314. object's hash(). If compare is true, the field will be used in
  315. comparison functions. metadata, if specified, must be a mapping
  316. which is stored but not otherwise examined by dataclass. If kw_only
  317. is true, the field will become a keyword-only parameter to
  318. __init__().
  319. It is an error to specify both default and default_factory.
  320. """
  321. if default is not MISSING and default_factory is not MISSING:
  322. raise ValueError('cannot specify both default and default_factory')
  323. return Field(default, default_factory, init, repr, hash, compare,
  324. metadata, kw_only)
  325. def _fields_in_init_order(fields):
  326. # Returns the fields as __init__ will output them. It returns 2 tuples:
  327. # the first for normal args, and the second for keyword args.
  328. return (tuple(f for f in fields if f.init and not f.kw_only),
  329. tuple(f for f in fields if f.init and f.kw_only)
  330. )
  331. def _tuple_str(obj_name, fields):
  332. # Return a string representing each field of obj_name as a tuple
  333. # member. So, if fields is ['x', 'y'] and obj_name is "self",
  334. # return "(self.x,self.y)".
  335. # Special case for the 0-tuple.
  336. if not fields:
  337. return '()'
  338. # Note the trailing comma, needed if this turns out to be a 1-tuple.
  339. return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)'
  340. # This function's logic is copied from "recursive_repr" function in
  341. # reprlib module to avoid dependency.
  342. def _recursive_repr(user_function):
  343. # Decorator to make a repr function return "..." for a recursive
  344. # call.
  345. repr_running = set()
  346. @functools.wraps(user_function)
  347. def wrapper(self):
  348. key = id(self), _thread.get_ident()
  349. if key in repr_running:
  350. return '...'
  351. repr_running.add(key)
  352. try:
  353. result = user_function(self)
  354. finally:
  355. repr_running.discard(key)
  356. return result
  357. return wrapper
  358. def _create_fn(name, args, body, *, globals=None, locals=None,
  359. return_type=MISSING):
  360. # Note that we mutate locals when exec() is called. Caller
  361. # beware! The only callers are internal to this module, so no
  362. # worries about external callers.
  363. if locals is None:
  364. locals = {}
  365. if 'BUILTINS' not in locals:
  366. locals['BUILTINS'] = builtins
  367. return_annotation = ''
  368. if return_type is not MISSING:
  369. locals['_return_type'] = return_type
  370. return_annotation = '->_return_type'
  371. args = ','.join(args)
  372. body = '\n'.join(f' {b}' for b in body)
  373. # Compute the text of the entire function.
  374. txt = f' def {name}({args}){return_annotation}:\n{body}'
  375. local_vars = ', '.join(locals.keys())
  376. txt = f"def __create_fn__({local_vars}):\n{txt}\n return {name}"
  377. ns = {}
  378. exec(txt, globals, ns)
  379. return ns['__create_fn__'](**locals)
  380. def _field_assign(frozen, name, value, self_name):
  381. # If we're a frozen class, then assign to our fields in __init__
  382. # via object.__setattr__. Otherwise, just use a simple
  383. # assignment.
  384. #
  385. # self_name is what "self" is called in this function: don't
  386. # hard-code "self", since that might be a field name.
  387. if frozen:
  388. return f'BUILTINS.object.__setattr__({self_name},{name!r},{value})'
  389. return f'{self_name}.{name}={value}'
  390. def _field_init(f, frozen, globals, self_name):
  391. # Return the text of the line in the body of __init__ that will
  392. # initialize this field.
  393. default_name = f'_dflt_{f.name}'
  394. if f.default_factory is not MISSING:
  395. if f.init:
  396. # This field has a default factory. If a parameter is
  397. # given, use it. If not, call the factory.
  398. globals[default_name] = f.default_factory
  399. value = (f'{default_name}() '
  400. f'if {f.name} is _HAS_DEFAULT_FACTORY '
  401. f'else {f.name}')
  402. else:
  403. # This is a field that's not in the __init__ params, but
  404. # has a default factory function. It needs to be
  405. # initialized here by calling the factory function,
  406. # because there's no other way to initialize it.
  407. # For a field initialized with a default=defaultvalue, the
  408. # class dict just has the default value
  409. # (cls.fieldname=defaultvalue). But that won't work for a
  410. # default factory, the factory must be called in __init__
  411. # and we must assign that to self.fieldname. We can't
  412. # fall back to the class dict's value, both because it's
  413. # not set, and because it might be different per-class
  414. # (which, after all, is why we have a factory function!).
  415. globals[default_name] = f.default_factory
  416. value = f'{default_name}()'
  417. else:
  418. # No default factory.
  419. if f.init:
  420. if f.default is MISSING:
  421. # There's no default, just do an assignment.
  422. value = f.name
  423. elif f.default is not MISSING:
  424. globals[default_name] = f.default
  425. value = f.name
  426. else:
  427. # This field does not need initialization. Signify that
  428. # to the caller by returning None.
  429. return None
  430. # Only test this now, so that we can create variables for the
  431. # default. However, return None to signify that we're not going
  432. # to actually do the assignment statement for InitVars.
  433. if f._field_type is _FIELD_INITVAR:
  434. return None
  435. # Now, actually generate the field assignment.
  436. return _field_assign(frozen, f.name, value, self_name)
  437. def _init_param(f):
  438. # Return the __init__ parameter string for this field. For
  439. # example, the equivalent of 'x:int=3' (except instead of 'int',
  440. # reference a variable set to int, and instead of '3', reference a
  441. # variable set to 3).
  442. if f.default is MISSING and f.default_factory is MISSING:
  443. # There's no default, and no default_factory, just output the
  444. # variable name and type.
  445. default = ''
  446. elif f.default is not MISSING:
  447. # There's a default, this will be the name that's used to look
  448. # it up.
  449. default = f'=_dflt_{f.name}'
  450. elif f.default_factory is not MISSING:
  451. # There's a factory function. Set a marker.
  452. default = '=_HAS_DEFAULT_FACTORY'
  453. return f'{f.name}:_type_{f.name}{default}'
  454. def _init_fn(fields, std_fields, kw_only_fields, frozen, has_post_init,
  455. self_name, globals):
  456. # fields contains both real fields and InitVar pseudo-fields.
  457. # Make sure we don't have fields without defaults following fields
  458. # with defaults. This actually would be caught when exec-ing the
  459. # function source code, but catching it here gives a better error
  460. # message, and future-proofs us in case we build up the function
  461. # using ast.
  462. seen_default = False
  463. for f in std_fields:
  464. # Only consider the non-kw-only fields in the __init__ call.
  465. if f.init:
  466. if not (f.default is MISSING and f.default_factory is MISSING):
  467. seen_default = True
  468. elif seen_default:
  469. raise TypeError(f'non-default argument {f.name!r} '
  470. 'follows default argument')
  471. locals = {f'_type_{f.name}': f.type for f in fields}
  472. locals.update({
  473. 'MISSING': MISSING,
  474. '_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY,
  475. })
  476. body_lines = []
  477. for f in fields:
  478. line = _field_init(f, frozen, locals, self_name)
  479. # line is None means that this field doesn't require
  480. # initialization (it's a pseudo-field). Just skip it.
  481. if line:
  482. body_lines.append(line)
  483. # Does this class have a post-init function?
  484. if has_post_init:
  485. params_str = ','.join(f.name for f in fields
  486. if f._field_type is _FIELD_INITVAR)
  487. body_lines.append(f'{self_name}.{_POST_INIT_NAME}({params_str})')
  488. # If no body lines, use 'pass'.
  489. if not body_lines:
  490. body_lines = ['pass']
  491. _init_params = [_init_param(f) for f in std_fields]
  492. if kw_only_fields:
  493. # Add the keyword-only args. Because the * can only be added if
  494. # there's at least one keyword-only arg, there needs to be a test here
  495. # (instead of just concatenting the lists together).
  496. _init_params += ['*']
  497. _init_params += [_init_param(f) for f in kw_only_fields]
  498. return _create_fn('__init__',
  499. [self_name] + _init_params,
  500. body_lines,
  501. locals=locals,
  502. globals=globals,
  503. return_type=None)
  504. def _repr_fn(fields, globals):
  505. fn = _create_fn('__repr__',
  506. ('self',),
  507. ['return self.__class__.__qualname__ + f"(' +
  508. ', '.join([f"{f.name}={{self.{f.name}!r}}"
  509. for f in fields]) +
  510. ')"'],
  511. globals=globals)
  512. return _recursive_repr(fn)
  513. def _frozen_get_del_attr(cls, fields, globals):
  514. locals = {'cls': cls,
  515. 'FrozenInstanceError': FrozenInstanceError}
  516. if fields:
  517. fields_str = '(' + ','.join(repr(f.name) for f in fields) + ',)'
  518. else:
  519. # Special case for the zero-length tuple.
  520. fields_str = '()'
  521. return (_create_fn('__setattr__',
  522. ('self', 'name', 'value'),
  523. (f'if type(self) is cls or name in {fields_str}:',
  524. ' raise FrozenInstanceError(f"cannot assign to field {name!r}")',
  525. f'super(cls, self).__setattr__(name, value)'),
  526. locals=locals,
  527. globals=globals),
  528. _create_fn('__delattr__',
  529. ('self', 'name'),
  530. (f'if type(self) is cls or name in {fields_str}:',
  531. ' raise FrozenInstanceError(f"cannot delete field {name!r}")',
  532. f'super(cls, self).__delattr__(name)'),
  533. locals=locals,
  534. globals=globals),
  535. )
  536. def _cmp_fn(name, op, self_tuple, other_tuple, globals):
  537. # Create a comparison function. If the fields in the object are
  538. # named 'x' and 'y', then self_tuple is the string
  539. # '(self.x,self.y)' and other_tuple is the string
  540. # '(other.x,other.y)'.
  541. return _create_fn(name,
  542. ('self', 'other'),
  543. [ 'if other.__class__ is self.__class__:',
  544. f' return {self_tuple}{op}{other_tuple}',
  545. 'return NotImplemented'],
  546. globals=globals)
  547. def _hash_fn(fields, globals):
  548. self_tuple = _tuple_str('self', fields)
  549. return _create_fn('__hash__',
  550. ('self',),
  551. [f'return hash({self_tuple})'],
  552. globals=globals)
  553. def _is_classvar(a_type, typing):
  554. # This test uses a typing internal class, but it's the best way to
  555. # test if this is a ClassVar.
  556. return (a_type is typing.ClassVar
  557. or (type(a_type) is typing._GenericAlias
  558. and a_type.__origin__ is typing.ClassVar))
  559. def _is_initvar(a_type, dataclasses):
  560. # The module we're checking against is the module we're
  561. # currently in (dataclasses.py).
  562. return (a_type is dataclasses.InitVar
  563. or type(a_type) is dataclasses.InitVar)
  564. def _is_kw_only(a_type, dataclasses):
  565. return a_type is dataclasses.KW_ONLY
  566. def _is_type(annotation, cls, a_module, a_type, is_type_predicate):
  567. # Given a type annotation string, does it refer to a_type in
  568. # a_module? For example, when checking that annotation denotes a
  569. # ClassVar, then a_module is typing, and a_type is
  570. # typing.ClassVar.
  571. # It's possible to look up a_module given a_type, but it involves
  572. # looking in sys.modules (again!), and seems like a waste since
  573. # the caller already knows a_module.
  574. # - annotation is a string type annotation
  575. # - cls is the class that this annotation was found in
  576. # - a_module is the module we want to match
  577. # - a_type is the type in that module we want to match
  578. # - is_type_predicate is a function called with (obj, a_module)
  579. # that determines if obj is of the desired type.
  580. # Since this test does not do a local namespace lookup (and
  581. # instead only a module (global) lookup), there are some things it
  582. # gets wrong.
  583. # With string annotations, cv0 will be detected as a ClassVar:
  584. # CV = ClassVar
  585. # @dataclass
  586. # class C0:
  587. # cv0: CV
  588. # But in this example cv1 will not be detected as a ClassVar:
  589. # @dataclass
  590. # class C1:
  591. # CV = ClassVar
  592. # cv1: CV
  593. # In C1, the code in this function (_is_type) will look up "CV" in
  594. # the module and not find it, so it will not consider cv1 as a
  595. # ClassVar. This is a fairly obscure corner case, and the best
  596. # way to fix it would be to eval() the string "CV" with the
  597. # correct global and local namespaces. However that would involve
  598. # a eval() penalty for every single field of every dataclass
  599. # that's defined. It was judged not worth it.
  600. match = _MODULE_IDENTIFIER_RE.match(annotation)
  601. if match:
  602. ns = None
  603. module_name = match.group(1)
  604. if not module_name:
  605. # No module name, assume the class's module did
  606. # "from dataclasses import InitVar".
  607. ns = sys.modules.get(cls.__module__).__dict__
  608. else:
  609. # Look up module_name in the class's module.
  610. module = sys.modules.get(cls.__module__)
  611. if module and module.__dict__.get(module_name) is a_module:
  612. ns = sys.modules.get(a_type.__module__).__dict__
  613. if ns and is_type_predicate(ns.get(match.group(2)), a_module):
  614. return True
  615. return False
  616. def _get_field(cls, a_name, a_type, default_kw_only):
  617. # Return a Field object for this field name and type. ClassVars and
  618. # InitVars are also returned, but marked as such (see f._field_type).
  619. # default_kw_only is the value of kw_only to use if there isn't a field()
  620. # that defines it.
  621. # If the default value isn't derived from Field, then it's only a
  622. # normal default value. Convert it to a Field().
  623. default = getattr(cls, a_name, MISSING)
  624. if isinstance(default, Field):
  625. f = default
  626. else:
  627. if isinstance(default, types.MemberDescriptorType):
  628. # This is a field in __slots__, so it has no default value.
  629. default = MISSING
  630. f = field(default=default)
  631. # Only at this point do we know the name and the type. Set them.
  632. f.name = a_name
  633. f.type = a_type
  634. # Assume it's a normal field until proven otherwise. We're next
  635. # going to decide if it's a ClassVar or InitVar, everything else
  636. # is just a normal field.
  637. f._field_type = _FIELD
  638. # In addition to checking for actual types here, also check for
  639. # string annotations. get_type_hints() won't always work for us
  640. # (see https://github.com/python/typing/issues/508 for example),
  641. # plus it's expensive and would require an eval for every string
  642. # annotation. So, make a best effort to see if this is a ClassVar
  643. # or InitVar using regex's and checking that the thing referenced
  644. # is actually of the correct type.
  645. # For the complete discussion, see https://bugs.python.org/issue33453
  646. # If typing has not been imported, then it's impossible for any
  647. # annotation to be a ClassVar. So, only look for ClassVar if
  648. # typing has been imported by any module (not necessarily cls's
  649. # module).
  650. typing = sys.modules.get('typing')
  651. if typing:
  652. if (_is_classvar(a_type, typing)
  653. or (isinstance(f.type, str)
  654. and _is_type(f.type, cls, typing, typing.ClassVar,
  655. _is_classvar))):
  656. f._field_type = _FIELD_CLASSVAR
  657. # If the type is InitVar, or if it's a matching string annotation,
  658. # then it's an InitVar.
  659. if f._field_type is _FIELD:
  660. # The module we're checking against is the module we're
  661. # currently in (dataclasses.py).
  662. dataclasses = sys.modules[__name__]
  663. if (_is_initvar(a_type, dataclasses)
  664. or (isinstance(f.type, str)
  665. and _is_type(f.type, cls, dataclasses, dataclasses.InitVar,
  666. _is_initvar))):
  667. f._field_type = _FIELD_INITVAR
  668. # Validations for individual fields. This is delayed until now,
  669. # instead of in the Field() constructor, since only here do we
  670. # know the field name, which allows for better error reporting.
  671. # Special restrictions for ClassVar and InitVar.
  672. if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR):
  673. if f.default_factory is not MISSING:
  674. raise TypeError(f'field {f.name} cannot have a '
  675. 'default factory')
  676. # Should I check for other field settings? default_factory
  677. # seems the most serious to check for. Maybe add others. For
  678. # example, how about init=False (or really,
  679. # init=<not-the-default-init-value>)? It makes no sense for
  680. # ClassVar and InitVar to specify init=<anything>.
  681. # kw_only validation and assignment.
  682. if f._field_type in (_FIELD, _FIELD_INITVAR):
  683. # For real and InitVar fields, if kw_only wasn't specified use the
  684. # default value.
  685. if f.kw_only is MISSING:
  686. f.kw_only = default_kw_only
  687. else:
  688. # Make sure kw_only isn't set for ClassVars
  689. assert f._field_type is _FIELD_CLASSVAR
  690. if f.kw_only is not MISSING:
  691. raise TypeError(f'field {f.name} is a ClassVar but specifies '
  692. 'kw_only')
  693. # For real fields, disallow mutable defaults for known types.
  694. if f._field_type is _FIELD and isinstance(f.default, (list, dict, set)):
  695. raise ValueError(f'mutable default {type(f.default)} for field '
  696. f'{f.name} is not allowed: use default_factory')
  697. return f
  698. def _set_qualname(cls, value):
  699. # Ensure that the functions returned from _create_fn uses the proper
  700. # __qualname__ (the class they belong to).
  701. if isinstance(value, FunctionType):
  702. value.__qualname__ = f"{cls.__qualname__}.{value.__name__}"
  703. return value
  704. def _set_new_attribute(cls, name, value):
  705. # Never overwrites an existing attribute. Returns True if the
  706. # attribute already exists.
  707. if name in cls.__dict__:
  708. return True
  709. _set_qualname(cls, value)
  710. setattr(cls, name, value)
  711. return False
  712. # Decide if/how we're going to create a hash function. Key is
  713. # (unsafe_hash, eq, frozen, does-hash-exist). Value is the action to
  714. # take. The common case is to do nothing, so instead of providing a
  715. # function that is a no-op, use None to signify that.
  716. def _hash_set_none(cls, fields, globals):
  717. return None
  718. def _hash_add(cls, fields, globals):
  719. flds = [f for f in fields if (f.compare if f.hash is None else f.hash)]
  720. return _set_qualname(cls, _hash_fn(flds, globals))
  721. def _hash_exception(cls, fields, globals):
  722. # Raise an exception.
  723. raise TypeError(f'Cannot overwrite attribute __hash__ '
  724. f'in class {cls.__name__}')
  725. #
  726. # +-------------------------------------- unsafe_hash?
  727. # | +------------------------------- eq?
  728. # | | +------------------------ frozen?
  729. # | | | +---------------- has-explicit-hash?
  730. # | | | |
  731. # | | | | +------- action
  732. # | | | | |
  733. # v v v v v
  734. _hash_action = {(False, False, False, False): None,
  735. (False, False, False, True ): None,
  736. (False, False, True, False): None,
  737. (False, False, True, True ): None,
  738. (False, True, False, False): _hash_set_none,
  739. (False, True, False, True ): None,
  740. (False, True, True, False): _hash_add,
  741. (False, True, True, True ): None,
  742. (True, False, False, False): _hash_add,
  743. (True, False, False, True ): _hash_exception,
  744. (True, False, True, False): _hash_add,
  745. (True, False, True, True ): _hash_exception,
  746. (True, True, False, False): _hash_add,
  747. (True, True, False, True ): _hash_exception,
  748. (True, True, True, False): _hash_add,
  749. (True, True, True, True ): _hash_exception,
  750. }
  751. # See https://bugs.python.org/issue32929#msg312829 for an if-statement
  752. # version of this table.
  753. def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen,
  754. match_args, kw_only, slots):
  755. # Now that dicts retain insertion order, there's no reason to use
  756. # an ordered dict. I am leveraging that ordering here, because
  757. # derived class fields overwrite base class fields, but the order
  758. # is defined by the base class, which is found first.
  759. fields = {}
  760. if cls.__module__ in sys.modules:
  761. globals = sys.modules[cls.__module__].__dict__
  762. else:
  763. # Theoretically this can happen if someone writes
  764. # a custom string to cls.__module__. In which case
  765. # such dataclass won't be fully introspectable
  766. # (w.r.t. typing.get_type_hints) but will still function
  767. # correctly.
  768. globals = {}
  769. setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order,
  770. unsafe_hash, frozen))
  771. # Find our base classes in reverse MRO order, and exclude
  772. # ourselves. In reversed order so that more derived classes
  773. # override earlier field definitions in base classes. As long as
  774. # we're iterating over them, see if any are frozen.
  775. any_frozen_base = False
  776. has_dataclass_bases = False
  777. for b in cls.__mro__[-1:0:-1]:
  778. # Only process classes that have been processed by our
  779. # decorator. That is, they have a _FIELDS attribute.
  780. base_fields = getattr(b, _FIELDS, None)
  781. if base_fields is not None:
  782. has_dataclass_bases = True
  783. for f in base_fields.values():
  784. fields[f.name] = f
  785. if getattr(b, _PARAMS).frozen:
  786. any_frozen_base = True
  787. # Annotations that are defined in this class (not in base
  788. # classes). If __annotations__ isn't present, then this class
  789. # adds no new annotations. We use this to compute fields that are
  790. # added by this class.
  791. #
  792. # Fields are found from cls_annotations, which is guaranteed to be
  793. # ordered. Default values are from class attributes, if a field
  794. # has a default. If the default value is a Field(), then it
  795. # contains additional info beyond (and possibly including) the
  796. # actual default value. Pseudo-fields ClassVars and InitVars are
  797. # included, despite the fact that they're not real fields. That's
  798. # dealt with later.
  799. cls_annotations = cls.__dict__.get('__annotations__', {})
  800. # Now find fields in our class. While doing so, validate some
  801. # things, and set the default values (as class attributes) where
  802. # we can.
  803. cls_fields = []
  804. # Get a reference to this module for the _is_kw_only() test.
  805. KW_ONLY_seen = False
  806. dataclasses = sys.modules[__name__]
  807. for name, type in cls_annotations.items():
  808. # See if this is a marker to change the value of kw_only.
  809. if (_is_kw_only(type, dataclasses)
  810. or (isinstance(type, str)
  811. and _is_type(type, cls, dataclasses, dataclasses.KW_ONLY,
  812. _is_kw_only))):
  813. # Switch the default to kw_only=True, and ignore this
  814. # annotation: it's not a real field.
  815. if KW_ONLY_seen:
  816. raise TypeError(f'{name!r} is KW_ONLY, but KW_ONLY '
  817. 'has already been specified')
  818. KW_ONLY_seen = True
  819. kw_only = True
  820. else:
  821. # Otherwise it's a field of some type.
  822. cls_fields.append(_get_field(cls, name, type, kw_only))
  823. for f in cls_fields:
  824. fields[f.name] = f
  825. # If the class attribute (which is the default value for this
  826. # field) exists and is of type 'Field', replace it with the
  827. # real default. This is so that normal class introspection
  828. # sees a real default value, not a Field.
  829. if isinstance(getattr(cls, f.name, None), Field):
  830. if f.default is MISSING:
  831. # If there's no default, delete the class attribute.
  832. # This happens if we specify field(repr=False), for
  833. # example (that is, we specified a field object, but
  834. # no default value). Also if we're using a default
  835. # factory. The class attribute should not be set at
  836. # all in the post-processed class.
  837. delattr(cls, f.name)
  838. else:
  839. setattr(cls, f.name, f.default)
  840. # Do we have any Field members that don't also have annotations?
  841. for name, value in cls.__dict__.items():
  842. if isinstance(value, Field) and not name in cls_annotations:
  843. raise TypeError(f'{name!r} is a field but has no type annotation')
  844. # Check rules that apply if we are derived from any dataclasses.
  845. if has_dataclass_bases:
  846. # Raise an exception if any of our bases are frozen, but we're not.
  847. if any_frozen_base and not frozen:
  848. raise TypeError('cannot inherit non-frozen dataclass from a '
  849. 'frozen one')
  850. # Raise an exception if we're frozen, but none of our bases are.
  851. if not any_frozen_base and frozen:
  852. raise TypeError('cannot inherit frozen dataclass from a '
  853. 'non-frozen one')
  854. # Remember all of the fields on our class (including bases). This
  855. # also marks this class as being a dataclass.
  856. setattr(cls, _FIELDS, fields)
  857. # Was this class defined with an explicit __hash__? Note that if
  858. # __eq__ is defined in this class, then python will automatically
  859. # set __hash__ to None. This is a heuristic, as it's possible
  860. # that such a __hash__ == None was not auto-generated, but it
  861. # close enough.
  862. class_hash = cls.__dict__.get('__hash__', MISSING)
  863. has_explicit_hash = not (class_hash is MISSING or
  864. (class_hash is None and '__eq__' in cls.__dict__))
  865. # If we're generating ordering methods, we must be generating the
  866. # eq methods.
  867. if order and not eq:
  868. raise ValueError('eq must be true if order is true')
  869. # Include InitVars and regular fields (so, not ClassVars). This is
  870. # initialized here, outside of the "if init:" test, because std_init_fields
  871. # is used with match_args, below.
  872. all_init_fields = [f for f in fields.values()
  873. if f._field_type in (_FIELD, _FIELD_INITVAR)]
  874. (std_init_fields,
  875. kw_only_init_fields) = _fields_in_init_order(all_init_fields)
  876. if init:
  877. # Does this class have a post-init function?
  878. has_post_init = hasattr(cls, _POST_INIT_NAME)
  879. _set_new_attribute(cls, '__init__',
  880. _init_fn(all_init_fields,
  881. std_init_fields,
  882. kw_only_init_fields,
  883. frozen,
  884. has_post_init,
  885. # The name to use for the "self"
  886. # param in __init__. Use "self"
  887. # if possible.
  888. '__dataclass_self__' if 'self' in fields
  889. else 'self',
  890. globals,
  891. ))
  892. # Get the fields as a list, and include only real fields. This is
  893. # used in all of the following methods.
  894. field_list = [f for f in fields.values() if f._field_type is _FIELD]
  895. if repr:
  896. flds = [f for f in field_list if f.repr]
  897. _set_new_attribute(cls, '__repr__', _repr_fn(flds, globals))
  898. if eq:
  899. # Create __eq__ method. There's no need for a __ne__ method,
  900. # since python will call __eq__ and negate it.
  901. flds = [f for f in field_list if f.compare]
  902. self_tuple = _tuple_str('self', flds)
  903. other_tuple = _tuple_str('other', flds)
  904. _set_new_attribute(cls, '__eq__',
  905. _cmp_fn('__eq__', '==',
  906. self_tuple, other_tuple,
  907. globals=globals))
  908. if order:
  909. # Create and set the ordering methods.
  910. flds = [f for f in field_list if f.compare]
  911. self_tuple = _tuple_str('self', flds)
  912. other_tuple = _tuple_str('other', flds)
  913. for name, op in [('__lt__', '<'),
  914. ('__le__', '<='),
  915. ('__gt__', '>'),
  916. ('__ge__', '>='),
  917. ]:
  918. if _set_new_attribute(cls, name,
  919. _cmp_fn(name, op, self_tuple, other_tuple,
  920. globals=globals)):
  921. raise TypeError(f'Cannot overwrite attribute {name} '
  922. f'in class {cls.__name__}. Consider using '
  923. 'functools.total_ordering')
  924. if frozen:
  925. for fn in _frozen_get_del_attr(cls, field_list, globals):
  926. if _set_new_attribute(cls, fn.__name__, fn):
  927. raise TypeError(f'Cannot overwrite attribute {fn.__name__} '
  928. f'in class {cls.__name__}')
  929. # Decide if/how we're going to create a hash function.
  930. hash_action = _hash_action[bool(unsafe_hash),
  931. bool(eq),
  932. bool(frozen),
  933. has_explicit_hash]
  934. if hash_action:
  935. # No need to call _set_new_attribute here, since by the time
  936. # we're here the overwriting is unconditional.
  937. cls.__hash__ = hash_action(cls, field_list, globals)
  938. if not getattr(cls, '__doc__'):
  939. # Create a class doc-string.
  940. cls.__doc__ = (cls.__name__ +
  941. str(inspect.signature(cls)).replace(' -> None', ''))
  942. if match_args:
  943. # I could probably compute this once
  944. _set_new_attribute(cls, '__match_args__',
  945. tuple(f.name for f in std_init_fields))
  946. if slots:
  947. cls = _add_slots(cls, frozen)
  948. abc.update_abstractmethods(cls)
  949. return cls
  950. # _dataclass_getstate and _dataclass_setstate are needed for pickling frozen
  951. # classes with slots. These could be slighly more performant if we generated
  952. # the code instead of iterating over fields. But that can be a project for
  953. # another day, if performance becomes an issue.
  954. def _dataclass_getstate(self):
  955. return [getattr(self, f.name) for f in fields(self)]
  956. def _dataclass_setstate(self, state):
  957. for field, value in zip(fields(self), state):
  958. # use setattr because dataclass may be frozen
  959. object.__setattr__(self, field.name, value)
  960. def _add_slots(cls, is_frozen):
  961. # Need to create a new class, since we can't set __slots__
  962. # after a class has been created.
  963. # Make sure __slots__ isn't already set.
  964. if '__slots__' in cls.__dict__:
  965. raise TypeError(f'{cls.__name__} already specifies __slots__')
  966. # Create a new dict for our new class.
  967. cls_dict = dict(cls.__dict__)
  968. field_names = tuple(f.name for f in fields(cls))
  969. cls_dict['__slots__'] = field_names
  970. for field_name in field_names:
  971. # Remove our attributes, if present. They'll still be
  972. # available in _MARKER.
  973. cls_dict.pop(field_name, None)
  974. # Remove __dict__ itself.
  975. cls_dict.pop('__dict__', None)
  976. # And finally create the class.
  977. qualname = getattr(cls, '__qualname__', None)
  978. cls = type(cls)(cls.__name__, cls.__bases__, cls_dict)
  979. if qualname is not None:
  980. cls.__qualname__ = qualname
  981. if is_frozen:
  982. # Need this for pickling frozen classes with slots.
  983. cls.__getstate__ = _dataclass_getstate
  984. cls.__setstate__ = _dataclass_setstate
  985. return cls
  986. def dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False,
  987. unsafe_hash=False, frozen=False, match_args=True,
  988. kw_only=False, slots=False):
  989. """Returns the same class as was passed in, with dunder methods
  990. added based on the fields defined in the class.
  991. Examines PEP 526 __annotations__ to determine fields.
  992. If init is true, an __init__() method is added to the class. If
  993. repr is true, a __repr__() method is added. If order is true, rich
  994. comparison dunder methods are added. If unsafe_hash is true, a
  995. __hash__() method function is added. If frozen is true, fields may
  996. not be assigned to after instance creation. If match_args is true,
  997. the __match_args__ tuple is added. If kw_only is true, then by
  998. default all fields are keyword-only. If slots is true, an
  999. __slots__ attribute is added.
  1000. """
  1001. def wrap(cls):
  1002. return _process_class(cls, init, repr, eq, order, unsafe_hash,
  1003. frozen, match_args, kw_only, slots)
  1004. # See if we're being called as @dataclass or @dataclass().
  1005. if cls is None:
  1006. # We're called with parens.
  1007. return wrap
  1008. # We're called as @dataclass without parens.
  1009. return wrap(cls)
  1010. def fields(class_or_instance):
  1011. """Return a tuple describing the fields of this dataclass.
  1012. Accepts a dataclass or an instance of one. Tuple elements are of
  1013. type Field.
  1014. """
  1015. # Might it be worth caching this, per class?
  1016. try:
  1017. fields = getattr(class_or_instance, _FIELDS)
  1018. except AttributeError:
  1019. raise TypeError('must be called with a dataclass type or instance')
  1020. # Exclude pseudo-fields. Note that fields is sorted by insertion
  1021. # order, so the order of the tuple is as the fields were defined.
  1022. return tuple(f for f in fields.values() if f._field_type is _FIELD)
  1023. def _is_dataclass_instance(obj):
  1024. """Returns True if obj is an instance of a dataclass."""
  1025. return hasattr(type(obj), _FIELDS)
  1026. def is_dataclass(obj):
  1027. """Returns True if obj is a dataclass or an instance of a
  1028. dataclass."""
  1029. cls = obj if isinstance(obj, type) else type(obj)
  1030. return hasattr(cls, _FIELDS)
  1031. def asdict(obj, *, dict_factory=dict):
  1032. """Return the fields of a dataclass instance as a new dictionary mapping
  1033. field names to field values.
  1034. Example usage:
  1035. @dataclass
  1036. class C:
  1037. x: int
  1038. y: int
  1039. c = C(1, 2)
  1040. assert asdict(c) == {'x': 1, 'y': 2}
  1041. If given, 'dict_factory' will be used instead of built-in dict.
  1042. The function applies recursively to field values that are
  1043. dataclass instances. This will also look into built-in containers:
  1044. tuples, lists, and dicts.
  1045. """
  1046. if not _is_dataclass_instance(obj):
  1047. raise TypeError("asdict() should be called on dataclass instances")
  1048. return _asdict_inner(obj, dict_factory)
  1049. def _asdict_inner(obj, dict_factory):
  1050. if _is_dataclass_instance(obj):
  1051. result = []
  1052. for f in fields(obj):
  1053. value = _asdict_inner(getattr(obj, f.name), dict_factory)
  1054. result.append((f.name, value))
  1055. return dict_factory(result)
  1056. elif isinstance(obj, tuple) and hasattr(obj, '_fields'):
  1057. # obj is a namedtuple. Recurse into it, but the returned
  1058. # object is another namedtuple of the same type. This is
  1059. # similar to how other list- or tuple-derived classes are
  1060. # treated (see below), but we just need to create them
  1061. # differently because a namedtuple's __init__ needs to be
  1062. # called differently (see bpo-34363).
  1063. # I'm not using namedtuple's _asdict()
  1064. # method, because:
  1065. # - it does not recurse in to the namedtuple fields and
  1066. # convert them to dicts (using dict_factory).
  1067. # - I don't actually want to return a dict here. The main
  1068. # use case here is json.dumps, and it handles converting
  1069. # namedtuples to lists. Admittedly we're losing some
  1070. # information here when we produce a json list instead of a
  1071. # dict. Note that if we returned dicts here instead of
  1072. # namedtuples, we could no longer call asdict() on a data
  1073. # structure where a namedtuple was used as a dict key.
  1074. return type(obj)(*[_asdict_inner(v, dict_factory) for v in obj])
  1075. elif isinstance(obj, (list, tuple)):
  1076. # Assume we can create an object of this type by passing in a
  1077. # generator (which is not true for namedtuples, handled
  1078. # above).
  1079. return type(obj)(_asdict_inner(v, dict_factory) for v in obj)
  1080. elif isinstance(obj, dict):
  1081. return type(obj)((_asdict_inner(k, dict_factory),
  1082. _asdict_inner(v, dict_factory))
  1083. for k, v in obj.items())
  1084. else:
  1085. return copy.deepcopy(obj)
  1086. def astuple(obj, *, tuple_factory=tuple):
  1087. """Return the fields of a dataclass instance as a new tuple of field values.
  1088. Example usage::
  1089. @dataclass
  1090. class C:
  1091. x: int
  1092. y: int
  1093. c = C(1, 2)
  1094. assert astuple(c) == (1, 2)
  1095. If given, 'tuple_factory' will be used instead of built-in tuple.
  1096. The function applies recursively to field values that are
  1097. dataclass instances. This will also look into built-in containers:
  1098. tuples, lists, and dicts.
  1099. """
  1100. if not _is_dataclass_instance(obj):
  1101. raise TypeError("astuple() should be called on dataclass instances")
  1102. return _astuple_inner(obj, tuple_factory)
  1103. def _astuple_inner(obj, tuple_factory):
  1104. if _is_dataclass_instance(obj):
  1105. result = []
  1106. for f in fields(obj):
  1107. value = _astuple_inner(getattr(obj, f.name), tuple_factory)
  1108. result.append(value)
  1109. return tuple_factory(result)
  1110. elif isinstance(obj, tuple) and hasattr(obj, '_fields'):
  1111. # obj is a namedtuple. Recurse into it, but the returned
  1112. # object is another namedtuple of the same type. This is
  1113. # similar to how other list- or tuple-derived classes are
  1114. # treated (see below), but we just need to create them
  1115. # differently because a namedtuple's __init__ needs to be
  1116. # called differently (see bpo-34363).
  1117. return type(obj)(*[_astuple_inner(v, tuple_factory) for v in obj])
  1118. elif isinstance(obj, (list, tuple)):
  1119. # Assume we can create an object of this type by passing in a
  1120. # generator (which is not true for namedtuples, handled
  1121. # above).
  1122. return type(obj)(_astuple_inner(v, tuple_factory) for v in obj)
  1123. elif isinstance(obj, dict):
  1124. return type(obj)((_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory))
  1125. for k, v in obj.items())
  1126. else:
  1127. return copy.deepcopy(obj)
  1128. def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
  1129. repr=True, eq=True, order=False, unsafe_hash=False,
  1130. frozen=False, match_args=True, slots=False):
  1131. """Return a new dynamically created dataclass.
  1132. The dataclass name will be 'cls_name'. 'fields' is an iterable
  1133. of either (name), (name, type) or (name, type, Field) objects. If type is
  1134. omitted, use the string 'typing.Any'. Field objects are created by
  1135. the equivalent of calling 'field(name, type [, Field-info])'.
  1136. C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,))
  1137. is equivalent to:
  1138. @dataclass
  1139. class C(Base):
  1140. x: 'typing.Any'
  1141. y: int
  1142. z: int = field(init=False)
  1143. For the bases and namespace parameters, see the builtin type() function.
  1144. The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to
  1145. dataclass().
  1146. """
  1147. if namespace is None:
  1148. namespace = {}
  1149. # While we're looking through the field names, validate that they
  1150. # are identifiers, are not keywords, and not duplicates.
  1151. seen = set()
  1152. annotations = {}
  1153. defaults = {}
  1154. for item in fields:
  1155. if isinstance(item, str):
  1156. name = item
  1157. tp = 'typing.Any'
  1158. elif len(item) == 2:
  1159. name, tp, = item
  1160. elif len(item) == 3:
  1161. name, tp, spec = item
  1162. defaults[name] = spec
  1163. else:
  1164. raise TypeError(f'Invalid field: {item!r}')
  1165. if not isinstance(name, str) or not name.isidentifier():
  1166. raise TypeError(f'Field names must be valid identifiers: {name!r}')
  1167. if keyword.iskeyword(name):
  1168. raise TypeError(f'Field names must not be keywords: {name!r}')
  1169. if name in seen:
  1170. raise TypeError(f'Field name duplicated: {name!r}')
  1171. seen.add(name)
  1172. annotations[name] = tp
  1173. # Update 'ns' with the user-supplied namespace plus our calculated values.
  1174. def exec_body_callback(ns):
  1175. ns.update(namespace)
  1176. ns.update(defaults)
  1177. ns['__annotations__'] = annotations
  1178. # We use `types.new_class()` instead of simply `type()` to allow dynamic creation
  1179. # of generic dataclassses.
  1180. cls = types.new_class(cls_name, bases, {}, exec_body_callback)
  1181. # Apply the normal decorator.
  1182. return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
  1183. unsafe_hash=unsafe_hash, frozen=frozen,
  1184. match_args=match_args, slots=slots)
  1185. def replace(obj, /, **changes):
  1186. """Return a new object replacing specified fields with new values.
  1187. This is especially useful for frozen classes. Example usage:
  1188. @dataclass(frozen=True)
  1189. class C:
  1190. x: int
  1191. y: int
  1192. c = C(1, 2)
  1193. c1 = replace(c, x=3)
  1194. assert c1.x == 3 and c1.y == 2
  1195. """
  1196. # We're going to mutate 'changes', but that's okay because it's a
  1197. # new dict, even if called with 'replace(obj, **my_changes)'.
  1198. if not _is_dataclass_instance(obj):
  1199. raise TypeError("replace() should be called on dataclass instances")
  1200. # It's an error to have init=False fields in 'changes'.
  1201. # If a field is not in 'changes', read its value from the provided obj.
  1202. for f in getattr(obj, _FIELDS).values():
  1203. # Only consider normal fields or InitVars.
  1204. if f._field_type is _FIELD_CLASSVAR:
  1205. continue
  1206. if not f.init:
  1207. # Error if this field is specified in changes.
  1208. if f.name in changes:
  1209. raise ValueError(f'field {f.name} is declared with '
  1210. 'init=False, it cannot be specified with '
  1211. 'replace()')
  1212. continue
  1213. if f.name not in changes:
  1214. if f._field_type is _FIELD_INITVAR and f.default is MISSING:
  1215. raise ValueError(f"InitVar {f.name!r} "
  1216. 'must be specified with replace()')
  1217. changes[f.name] = getattr(obj, f.name)
  1218. # Create the new object, which calls __init__() and
  1219. # __post_init__() (if defined), using all of the init fields we've
  1220. # added and/or left in 'changes'. If there are values supplied in
  1221. # changes that aren't fields, this will correctly raise a
  1222. # TypeError.
  1223. return obj.__class__(**changes)