dataclasses.py 48 KB

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