dataclasses.py 56 KB

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