dataclasses.py 48 KB

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