blob: 036349bfbda731e8916c53b2aa09777e47be4ab3 [file] [log] [blame]
Eric V. Smith2a7bacb2018-05-15 22:44:27 -04001import re
Eric V. Smithf0db54a2017-12-04 16:58:55 -05002import sys
Eric V. Smithf96ddad2018-03-24 17:20:26 -04003import copy
Eric V. Smithf0db54a2017-12-04 16:58:55 -05004import types
Eric V. Smithf0db54a2017-12-04 16:58:55 -05005import inspect
Eric V. Smith4e812962018-05-16 11:31:29 -04006import keyword
Vadim Pushtaev4d12e4d2018-08-12 14:46:05 +03007import builtins
Srinivas Thatiparthy (శ్రీనివాస్ తాటిపర్తి)dd13c882018-10-19 22:24:50 +05308import functools
Ben Avrahamibef7d292020-10-06 20:40:50 +03009import abc
Srinivas Thatiparthy (శ్రీనివాస్ తాటిపర్తి)dd13c882018-10-19 22:24:50 +053010import _thread
Batuhan Taskayac7437e22020-10-21 16:49:22 +030011from types import FunctionType, GenericAlias
Srinivas Thatiparthy (శ్రీనివాస్ తాటిపర్తి)dd13c882018-10-19 22:24:50 +053012
Eric V. Smithf0db54a2017-12-04 16:58:55 -050013
14__all__ = ['dataclass',
15 'field',
Eric V. Smith8e4560a2018-03-21 17:10:22 -040016 'Field',
Eric V. Smithf0db54a2017-12-04 16:58:55 -050017 'FrozenInstanceError',
18 'InitVar',
Eric V. Smith03220fd2017-12-29 13:59:58 -050019 'MISSING',
Eric V. Smithf0db54a2017-12-04 16:58:55 -050020
21 # Helper functions.
22 'fields',
23 'asdict',
24 'astuple',
25 'make_dataclass',
26 'replace',
Eric V. Smithe7ba0132018-01-06 12:41:53 -050027 'is_dataclass',
Eric V. Smithf0db54a2017-12-04 16:58:55 -050028 ]
29
Eric V. Smithea8fc522018-01-27 19:07:40 -050030# Conditions for adding methods. The boxes indicate what action the
Eric V. Smithf8e75492018-05-16 05:14:53 -040031# dataclass decorator takes. For all of these tables, when I talk
32# about init=, repr=, eq=, order=, unsafe_hash=, or frozen=, I'm
33# referring to the arguments to the @dataclass decorator. When
34# checking if a dunder method already exists, I mean check for an
35# entry in the class's __dict__. I never check to see if an attribute
36# is defined in a base class.
Eric V. Smithea8fc522018-01-27 19:07:40 -050037
38# Key:
39# +=========+=========================================+
40# + Value | Meaning |
41# +=========+=========================================+
42# | <blank> | No action: no method is added. |
43# +---------+-----------------------------------------+
44# | add | Generated method is added. |
45# +---------+-----------------------------------------+
Eric V. Smithea8fc522018-01-27 19:07:40 -050046# | raise | TypeError is raised. |
47# +---------+-----------------------------------------+
48# | None | Attribute is set to None. |
49# +=========+=========================================+
50
51# __init__
52#
53# +--- init= parameter
54# |
55# v | | |
56# | no | yes | <--- class has __init__ in __dict__?
57# +=======+=======+=======+
58# | False | | |
59# +-------+-------+-------+
60# | True | add | | <- the default
61# +=======+=======+=======+
62
63# __repr__
64#
65# +--- repr= parameter
66# |
67# v | | |
68# | no | yes | <--- class has __repr__ in __dict__?
69# +=======+=======+=======+
70# | False | | |
71# +-------+-------+-------+
72# | True | add | | <- the default
73# +=======+=======+=======+
74
75
76# __setattr__
77# __delattr__
78#
79# +--- frozen= parameter
80# |
81# v | | |
82# | no | yes | <--- class has __setattr__ or __delattr__ in __dict__?
83# +=======+=======+=======+
84# | False | | | <- the default
85# +-------+-------+-------+
86# | True | add | raise |
87# +=======+=======+=======+
88# Raise because not adding these methods would break the "frozen-ness"
Eric V. Smithf8e75492018-05-16 05:14:53 -040089# of the class.
Eric V. Smithea8fc522018-01-27 19:07:40 -050090
91# __eq__
92#
93# +--- eq= parameter
94# |
95# v | | |
96# | no | yes | <--- class has __eq__ in __dict__?
97# +=======+=======+=======+
98# | False | | |
99# +-------+-------+-------+
100# | True | add | | <- the default
101# +=======+=======+=======+
102
103# __lt__
104# __le__
105# __gt__
106# __ge__
107#
108# +--- order= parameter
109# |
110# v | | |
111# | no | yes | <--- class has any comparison method in __dict__?
112# +=======+=======+=======+
113# | False | | | <- the default
114# +-------+-------+-------+
115# | True | add | raise |
116# +=======+=======+=======+
117# Raise because to allow this case would interfere with using
Eric V. Smithf8e75492018-05-16 05:14:53 -0400118# functools.total_ordering.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500119
120# __hash__
121
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500122# +------------------- unsafe_hash= parameter
123# | +----------- eq= parameter
124# | | +--- frozen= parameter
125# | | |
126# v v v | | |
127# | no | yes | <--- class has explicitly defined __hash__
128# +=======+=======+=======+========+========+
129# | False | False | False | | | No __eq__, use the base class __hash__
130# +-------+-------+-------+--------+--------+
131# | False | False | True | | | No __eq__, use the base class __hash__
132# +-------+-------+-------+--------+--------+
133# | False | True | False | None | | <-- the default, not hashable
134# +-------+-------+-------+--------+--------+
135# | False | True | True | add | | Frozen, so hashable, allows override
136# +-------+-------+-------+--------+--------+
137# | True | False | False | add | raise | Has no __eq__, but hashable
138# +-------+-------+-------+--------+--------+
139# | True | False | True | add | raise | Has no __eq__, but hashable
140# +-------+-------+-------+--------+--------+
141# | True | True | False | add | raise | Not frozen, but hashable
142# +-------+-------+-------+--------+--------+
143# | True | True | True | add | raise | Frozen, so hashable
144# +=======+=======+=======+========+========+
Eric V. Smithea8fc522018-01-27 19:07:40 -0500145# For boxes that are blank, __hash__ is untouched and therefore
Eric V. Smithf8e75492018-05-16 05:14:53 -0400146# inherited from the base class. If the base is object, then
147# id-based hashing is used.
148#
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400149# Note that a class may already have __hash__=None if it specified an
Eric V. Smithf8e75492018-05-16 05:14:53 -0400150# __eq__ method in the class body (not one that was created by
151# @dataclass).
152#
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500153# See _hash_action (below) for a coded version of this table.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500154
Brandt Bucher145bf262021-02-26 14:51:55 -0800155# __match_args__
156#
Eric V. Smith750f4842021-04-10 21:28:42 -0400157# +--- match_args= parameter
158# |
159# v | | |
160# | no | yes | <--- class has __match_args__ in __dict__?
161# +=======+=======+=======+
162# | False | | |
163# +-------+-------+-------+
164# | True | add | | <- the default
165# +=======+=======+=======+
166# __match_args__ is a tuple of __init__ parameter names; non-init fields must
167# be matched by keyword.
Brandt Bucher145bf262021-02-26 14:51:55 -0800168
Eric V. Smithea8fc522018-01-27 19:07:40 -0500169
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500170# Raised when an attempt is made to modify a frozen class.
171class FrozenInstanceError(AttributeError): pass
172
Eric V. Smithf8e75492018-05-16 05:14:53 -0400173# A sentinel object for default values to signal that a default
174# factory will be used. This is given a nice repr() which will appear
175# in the function signature of dataclasses' constructors.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500176class _HAS_DEFAULT_FACTORY_CLASS:
177 def __repr__(self):
178 return '<factory>'
179_HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS()
180
Eric V. Smith03220fd2017-12-29 13:59:58 -0500181# A sentinel object to detect if a parameter is supplied or not. Use
Eric V. Smithf8e75492018-05-16 05:14:53 -0400182# a class to give it a better repr.
Eric V. Smith03220fd2017-12-29 13:59:58 -0500183class _MISSING_TYPE:
184 pass
185MISSING = _MISSING_TYPE()
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500186
187# Since most per-field metadata will be unused, create an empty
Eric V. Smithf8e75492018-05-16 05:14:53 -0400188# read-only proxy that can be shared among all fields.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500189_EMPTY_METADATA = types.MappingProxyType({})
190
191# Markers for the various kinds of fields and pseudo-fields.
Eric V. Smith01abc6e2018-05-15 08:36:21 -0400192class _FIELD_BASE:
193 def __init__(self, name):
194 self.name = name
195 def __repr__(self):
196 return self.name
197_FIELD = _FIELD_BASE('_FIELD')
198_FIELD_CLASSVAR = _FIELD_BASE('_FIELD_CLASSVAR')
199_FIELD_INITVAR = _FIELD_BASE('_FIELD_INITVAR')
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500200
201# The name of an attribute on the class where we store the Field
Eric V. Smithf8e75492018-05-16 05:14:53 -0400202# objects. Also used to check if a class is a Data Class.
Eric V. Smithf199bc62018-03-18 20:40:34 -0400203_FIELDS = '__dataclass_fields__'
204
205# The name of an attribute on the class that stores the parameters to
206# @dataclass.
207_PARAMS = '__dataclass_params__'
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500208
209# The name of the function, that if it exists, is called at the end of
210# __init__.
211_POST_INIT_NAME = '__post_init__'
212
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400213# String regex that string annotations for ClassVar or InitVar must match.
214# Allows "identifier.identifier[" or "identifier[".
215# https://bugs.python.org/issue33453 for details.
216_MODULE_IDENTIFIER_RE = re.compile(r'^(?:\s*(\w+)\s*\.)?\s*(\w+)')
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500217
Serhiy Storchakab4d0b392019-09-22 13:32:41 +0300218class InitVar:
Augusto Hack01ee12b2019-06-02 23:14:48 -0300219 __slots__ = ('type', )
220
221 def __init__(self, type):
222 self.type = type
223
224 def __repr__(self):
Samuel Colvin793cb852019-10-13 12:45:36 +0100225 if isinstance(self.type, type):
226 type_name = self.type.__name__
227 else:
228 # typing objects, e.g. List[int]
229 type_name = repr(self.type)
230 return f'dataclasses.InitVar[{type_name}]'
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500231
Serhiy Storchakab4d0b392019-09-22 13:32:41 +0300232 def __class_getitem__(cls, type):
233 return InitVar(type)
234
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500235
236# Instances of Field are only ever created from within this module,
Eric V. Smithf8e75492018-05-16 05:14:53 -0400237# and only from the field() function, although Field instances are
238# exposed externally as (conceptually) read-only objects.
239#
240# name and type are filled in after the fact, not in __init__.
241# They're not known at the time this class is instantiated, but it's
242# convenient if they're available later.
243#
Eric V. Smithf199bc62018-03-18 20:40:34 -0400244# When cls._FIELDS is filled in with a list of Field objects, the name
Eric V. Smithf8e75492018-05-16 05:14:53 -0400245# and type fields will have been populated.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500246class Field:
247 __slots__ = ('name',
248 'type',
249 'default',
250 'default_factory',
251 'repr',
252 'hash',
253 'init',
254 'compare',
255 'metadata',
256 '_field_type', # Private: not to be used by user code.
257 )
258
259 def __init__(self, default, default_factory, init, repr, hash, compare,
260 metadata):
261 self.name = None
262 self.type = None
263 self.default = default
264 self.default_factory = default_factory
265 self.init = init
266 self.repr = repr
267 self.hash = hash
268 self.compare = compare
269 self.metadata = (_EMPTY_METADATA
Christopher Huntb01786c2019-02-12 06:50:49 -0500270 if metadata is None else
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500271 types.MappingProxyType(metadata))
272 self._field_type = None
273
274 def __repr__(self):
275 return ('Field('
276 f'name={self.name!r},'
Eric V. Smith2473eea2018-05-14 11:37:28 -0400277 f'type={self.type!r},'
278 f'default={self.default!r},'
279 f'default_factory={self.default_factory!r},'
280 f'init={self.init!r},'
281 f'repr={self.repr!r},'
282 f'hash={self.hash!r},'
283 f'compare={self.compare!r},'
Eric V. Smith01abc6e2018-05-15 08:36:21 -0400284 f'metadata={self.metadata!r},'
285 f'_field_type={self._field_type}'
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500286 ')')
287
Eric V. Smithde7a2f02018-03-26 13:29:16 -0400288 # This is used to support the PEP 487 __set_name__ protocol in the
Eric V. Smithf8e75492018-05-16 05:14:53 -0400289 # case where we're using a field that contains a descriptor as a
Artjome55ca3f2018-07-06 02:09:13 +0300290 # default value. For details on __set_name__, see
Eric V. Smithf8e75492018-05-16 05:14:53 -0400291 # https://www.python.org/dev/peps/pep-0487/#implementation-details.
292 #
293 # Note that in _process_class, this Field object is overwritten
294 # with the default value, so the end result is a descriptor that
295 # had __set_name__ called on it at the right time.
Eric V. Smithde7a2f02018-03-26 13:29:16 -0400296 def __set_name__(self, owner, name):
Eric V. Smith52199522018-03-29 11:07:48 -0400297 func = getattr(type(self.default), '__set_name__', None)
Eric V. Smithde7a2f02018-03-26 13:29:16 -0400298 if func:
Eric V. Smithf8e75492018-05-16 05:14:53 -0400299 # There is a __set_name__ method on the descriptor, call
300 # it.
Eric V. Smith52199522018-03-29 11:07:48 -0400301 func(self.default, owner, name)
Eric V. Smithde7a2f02018-03-26 13:29:16 -0400302
Ethan Smithd01628e2020-04-14 16:14:15 -0700303 __class_getitem__ = classmethod(GenericAlias)
304
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500305
Eric V. Smithf199bc62018-03-18 20:40:34 -0400306class _DataclassParams:
307 __slots__ = ('init',
308 'repr',
309 'eq',
310 'order',
311 'unsafe_hash',
312 'frozen',
313 )
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400314
Eric V. Smithf199bc62018-03-18 20:40:34 -0400315 def __init__(self, init, repr, eq, order, unsafe_hash, frozen):
316 self.init = init
317 self.repr = repr
318 self.eq = eq
319 self.order = order
320 self.unsafe_hash = unsafe_hash
321 self.frozen = frozen
322
323 def __repr__(self):
324 return ('_DataclassParams('
Eric V. Smith30590422018-05-14 17:16:52 -0400325 f'init={self.init!r},'
326 f'repr={self.repr!r},'
327 f'eq={self.eq!r},'
328 f'order={self.order!r},'
329 f'unsafe_hash={self.unsafe_hash!r},'
330 f'frozen={self.frozen!r}'
Eric V. Smithf199bc62018-03-18 20:40:34 -0400331 ')')
332
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400333
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500334# This function is used instead of exposing Field creation directly,
Eric V. Smithf8e75492018-05-16 05:14:53 -0400335# so that a type checker can be told (via overloads) that this is a
336# function whose type depends on its parameters.
Eric V. Smith03220fd2017-12-29 13:59:58 -0500337def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True,
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500338 hash=None, compare=True, metadata=None):
339 """Return an object to identify dataclass fields.
340
Eric V. Smithf8e75492018-05-16 05:14:53 -0400341 default is the default value of the field. default_factory is a
342 0-argument function called to initialize a field's value. If init
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500343 is True, the field will be a parameter to the class's __init__()
Eric V. Smithf8e75492018-05-16 05:14:53 -0400344 function. If repr is True, the field will be included in the
345 object's repr(). If hash is True, the field will be included in
346 the object's hash(). If compare is True, the field will be used
347 in comparison functions. metadata, if specified, must be a
348 mapping which is stored but not otherwise examined by dataclass.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500349
350 It is an error to specify both default and default_factory.
351 """
352
Eric V. Smith03220fd2017-12-29 13:59:58 -0500353 if default is not MISSING and default_factory is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500354 raise ValueError('cannot specify both default and default_factory')
355 return Field(default, default_factory, init, repr, hash, compare,
356 metadata)
357
358
359def _tuple_str(obj_name, fields):
360 # Return a string representing each field of obj_name as a tuple
Eric V. Smithf8e75492018-05-16 05:14:53 -0400361 # member. So, if fields is ['x', 'y'] and obj_name is "self",
362 # return "(self.x,self.y)".
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500363
364 # Special case for the 0-tuple.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500365 if not fields:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500366 return '()'
367 # Note the trailing comma, needed if this turns out to be a 1-tuple.
368 return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)'
369
370
Srinivas Thatiparthy (శ్రీనివాస్ తాటిపర్తి)dd13c882018-10-19 22:24:50 +0530371# This function's logic is copied from "recursive_repr" function in
372# reprlib module to avoid dependency.
373def _recursive_repr(user_function):
374 # Decorator to make a repr function return "..." for a recursive
375 # call.
376 repr_running = set()
377
378 @functools.wraps(user_function)
379 def wrapper(self):
380 key = id(self), _thread.get_ident()
381 if key in repr_running:
382 return '...'
383 repr_running.add(key)
384 try:
385 result = user_function(self)
386 finally:
387 repr_running.discard(key)
388 return result
389 return wrapper
390
391
Eric V. Smithea8fc522018-01-27 19:07:40 -0500392def _create_fn(name, args, body, *, globals=None, locals=None,
Eric V. Smith03220fd2017-12-29 13:59:58 -0500393 return_type=MISSING):
Eric V. Smithf8e75492018-05-16 05:14:53 -0400394 # Note that we mutate locals when exec() is called. Caller
395 # beware! The only callers are internal to this module, so no
396 # worries about external callers.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500397 if locals is None:
398 locals = {}
Yury Selivanovd219cc42019-12-09 09:54:20 -0500399 if 'BUILTINS' not in locals:
400 locals['BUILTINS'] = builtins
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500401 return_annotation = ''
Eric V. Smith03220fd2017-12-29 13:59:58 -0500402 if return_type is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500403 locals['_return_type'] = return_type
404 return_annotation = '->_return_type'
405 args = ','.join(args)
Yury Selivanovd219cc42019-12-09 09:54:20 -0500406 body = '\n'.join(f' {b}' for b in body)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500407
Eric V. Smithf199bc62018-03-18 20:40:34 -0400408 # Compute the text of the entire function.
Yury Selivanovd219cc42019-12-09 09:54:20 -0500409 txt = f' def {name}({args}){return_annotation}:\n{body}'
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500410
Yury Selivanovd219cc42019-12-09 09:54:20 -0500411 local_vars = ', '.join(locals.keys())
412 txt = f"def __create_fn__({local_vars}):\n{txt}\n return {name}"
413
414 ns = {}
415 exec(txt, globals, ns)
Pablo Galindob0544ba2021-04-21 12:41:19 +0100416 return ns['__create_fn__'](**locals)
417
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500418
419def _field_assign(frozen, name, value, self_name):
420 # If we're a frozen class, then assign to our fields in __init__
Eric V. Smithf8e75492018-05-16 05:14:53 -0400421 # via object.__setattr__. Otherwise, just use a simple
422 # assignment.
423 #
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500424 # self_name is what "self" is called in this function: don't
Eric V. Smithf8e75492018-05-16 05:14:53 -0400425 # hard-code "self", since that might be a field name.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500426 if frozen:
Yury Selivanovd219cc42019-12-09 09:54:20 -0500427 return f'BUILTINS.object.__setattr__({self_name},{name!r},{value})'
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500428 return f'{self_name}.{name}={value}'
429
430
431def _field_init(f, frozen, globals, self_name):
432 # Return the text of the line in the body of __init__ that will
Eric V. Smithf8e75492018-05-16 05:14:53 -0400433 # initialize this field.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500434
435 default_name = f'_dflt_{f.name}'
Eric V. Smith03220fd2017-12-29 13:59:58 -0500436 if f.default_factory is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500437 if f.init:
438 # This field has a default factory. If a parameter is
Eric V. Smithf8e75492018-05-16 05:14:53 -0400439 # given, use it. If not, call the factory.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500440 globals[default_name] = f.default_factory
441 value = (f'{default_name}() '
442 f'if {f.name} is _HAS_DEFAULT_FACTORY '
443 f'else {f.name}')
444 else:
445 # This is a field that's not in the __init__ params, but
Eric V. Smithf8e75492018-05-16 05:14:53 -0400446 # has a default factory function. It needs to be
447 # initialized here by calling the factory function,
448 # because there's no other way to initialize it.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500449
450 # For a field initialized with a default=defaultvalue, the
Eric V. Smithf8e75492018-05-16 05:14:53 -0400451 # class dict just has the default value
452 # (cls.fieldname=defaultvalue). But that won't work for a
453 # default factory, the factory must be called in __init__
454 # and we must assign that to self.fieldname. We can't
455 # fall back to the class dict's value, both because it's
456 # not set, and because it might be different per-class
457 # (which, after all, is why we have a factory function!).
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500458
459 globals[default_name] = f.default_factory
460 value = f'{default_name}()'
461 else:
462 # No default factory.
463 if f.init:
Eric V. Smith03220fd2017-12-29 13:59:58 -0500464 if f.default is MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500465 # There's no default, just do an assignment.
466 value = f.name
Eric V. Smith03220fd2017-12-29 13:59:58 -0500467 elif f.default is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500468 globals[default_name] = f.default
469 value = f.name
470 else:
Eric V. Smithf8e75492018-05-16 05:14:53 -0400471 # This field does not need initialization. Signify that
472 # to the caller by returning None.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500473 return None
474
475 # Only test this now, so that we can create variables for the
Eric V. Smithf8e75492018-05-16 05:14:53 -0400476 # default. However, return None to signify that we're not going
477 # to actually do the assignment statement for InitVars.
Eric V. Smithe7adf2b2018-06-07 14:43:59 -0400478 if f._field_type is _FIELD_INITVAR:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500479 return None
480
481 # Now, actually generate the field assignment.
482 return _field_assign(frozen, f.name, value, self_name)
483
484
485def _init_param(f):
Eric V. Smithf8e75492018-05-16 05:14:53 -0400486 # Return the __init__ parameter string for this field. For
487 # example, the equivalent of 'x:int=3' (except instead of 'int',
488 # reference a variable set to int, and instead of '3', reference a
489 # variable set to 3).
Eric V. Smith03220fd2017-12-29 13:59:58 -0500490 if f.default is MISSING and f.default_factory is MISSING:
Eric V. Smithf8e75492018-05-16 05:14:53 -0400491 # There's no default, and no default_factory, just output the
492 # variable name and type.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500493 default = ''
Eric V. Smith03220fd2017-12-29 13:59:58 -0500494 elif f.default is not MISSING:
Eric V. Smithf8e75492018-05-16 05:14:53 -0400495 # There's a default, this will be the name that's used to look
496 # it up.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500497 default = f'=_dflt_{f.name}'
Eric V. Smith03220fd2017-12-29 13:59:58 -0500498 elif f.default_factory is not MISSING:
Eric V. Smithf8e75492018-05-16 05:14:53 -0400499 # There's a factory function. Set a marker.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500500 default = '=_HAS_DEFAULT_FACTORY'
501 return f'{f.name}:_type_{f.name}{default}'
502
503
Yury Selivanovd219cc42019-12-09 09:54:20 -0500504def _init_fn(fields, frozen, has_post_init, self_name, globals):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500505 # fields contains both real fields and InitVar pseudo-fields.
506
507 # Make sure we don't have fields without defaults following fields
Eric V. Smithf8e75492018-05-16 05:14:53 -0400508 # with defaults. This actually would be caught when exec-ing the
509 # function source code, but catching it here gives a better error
510 # message, and future-proofs us in case we build up the function
511 # using ast.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500512 seen_default = False
513 for f in fields:
514 # Only consider fields in the __init__ call.
515 if f.init:
Eric V. Smith03220fd2017-12-29 13:59:58 -0500516 if not (f.default is MISSING and f.default_factory is MISSING):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500517 seen_default = True
518 elif seen_default:
519 raise TypeError(f'non-default argument {f.name!r} '
520 'follows default argument')
521
Yury Selivanovd219cc42019-12-09 09:54:20 -0500522 locals = {f'_type_{f.name}': f.type for f in fields}
523 locals.update({
524 'MISSING': MISSING,
525 '_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY,
526 })
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500527
528 body_lines = []
529 for f in fields:
Yury Selivanovd219cc42019-12-09 09:54:20 -0500530 line = _field_init(f, frozen, locals, self_name)
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400531 # line is None means that this field doesn't require
Eric V. Smithf8e75492018-05-16 05:14:53 -0400532 # initialization (it's a pseudo-field). Just skip it.
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400533 if line:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500534 body_lines.append(line)
535
536 # Does this class have a post-init function?
537 if has_post_init:
538 params_str = ','.join(f.name for f in fields
539 if f._field_type is _FIELD_INITVAR)
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400540 body_lines.append(f'{self_name}.{_POST_INIT_NAME}({params_str})')
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500541
542 # If no body lines, use 'pass'.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500543 if not body_lines:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500544 body_lines = ['pass']
545
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500546 return _create_fn('__init__',
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400547 [self_name] + [_init_param(f) for f in fields if f.init],
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500548 body_lines,
549 locals=locals,
550 globals=globals,
551 return_type=None)
552
553
Yury Selivanovd219cc42019-12-09 09:54:20 -0500554def _repr_fn(fields, globals):
Srinivas Thatiparthy (శ్రీనివాస్ తాటిపర్తి)dd13c882018-10-19 22:24:50 +0530555 fn = _create_fn('__repr__',
556 ('self',),
557 ['return self.__class__.__qualname__ + f"(' +
558 ', '.join([f"{f.name}={{self.{f.name}!r}}"
559 for f in fields]) +
Yury Selivanovd219cc42019-12-09 09:54:20 -0500560 ')"'],
561 globals=globals)
Srinivas Thatiparthy (శ్రీనివాస్ తాటిపర్తి)dd13c882018-10-19 22:24:50 +0530562 return _recursive_repr(fn)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500563
564
Yury Selivanovd219cc42019-12-09 09:54:20 -0500565def _frozen_get_del_attr(cls, fields, globals):
566 locals = {'cls': cls,
Eric V. Smithf199bc62018-03-18 20:40:34 -0400567 'FrozenInstanceError': FrozenInstanceError}
568 if fields:
569 fields_str = '(' + ','.join(repr(f.name) for f in fields) + ',)'
570 else:
571 # Special case for the zero-length tuple.
572 fields_str = '()'
573 return (_create_fn('__setattr__',
574 ('self', 'name', 'value'),
575 (f'if type(self) is cls or name in {fields_str}:',
576 ' raise FrozenInstanceError(f"cannot assign to field {name!r}")',
577 f'super(cls, self).__setattr__(name, value)'),
Yury Selivanovd219cc42019-12-09 09:54:20 -0500578 locals=locals,
Eric V. Smithf199bc62018-03-18 20:40:34 -0400579 globals=globals),
580 _create_fn('__delattr__',
581 ('self', 'name'),
582 (f'if type(self) is cls or name in {fields_str}:',
583 ' raise FrozenInstanceError(f"cannot delete field {name!r}")',
584 f'super(cls, self).__delattr__(name)'),
Yury Selivanovd219cc42019-12-09 09:54:20 -0500585 locals=locals,
Eric V. Smithf199bc62018-03-18 20:40:34 -0400586 globals=globals),
587 )
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500588
589
Yury Selivanovd219cc42019-12-09 09:54:20 -0500590def _cmp_fn(name, op, self_tuple, other_tuple, globals):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500591 # Create a comparison function. If the fields in the object are
Eric V. Smithf8e75492018-05-16 05:14:53 -0400592 # named 'x' and 'y', then self_tuple is the string
593 # '(self.x,self.y)' and other_tuple is the string
594 # '(other.x,other.y)'.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500595
596 return _create_fn(name,
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400597 ('self', 'other'),
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500598 [ 'if other.__class__ is self.__class__:',
599 f' return {self_tuple}{op}{other_tuple}',
Yury Selivanovd219cc42019-12-09 09:54:20 -0500600 'return NotImplemented'],
601 globals=globals)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500602
603
Yury Selivanovd219cc42019-12-09 09:54:20 -0500604def _hash_fn(fields, globals):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500605 self_tuple = _tuple_str('self', fields)
606 return _create_fn('__hash__',
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400607 ('self',),
Yury Selivanovd219cc42019-12-09 09:54:20 -0500608 [f'return hash({self_tuple})'],
609 globals=globals)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500610
611
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400612def _is_classvar(a_type, typing):
Eric V. Smith92858352018-05-16 07:24:00 -0400613 # This test uses a typing internal class, but it's the best way to
614 # test if this is a ClassVar.
615 return (a_type is typing.ClassVar
616 or (type(a_type) is typing._GenericAlias
617 and a_type.__origin__ is typing.ClassVar))
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400618
619
620def _is_initvar(a_type, dataclasses):
621 # The module we're checking against is the module we're
622 # currently in (dataclasses.py).
Augusto Hack01ee12b2019-06-02 23:14:48 -0300623 return (a_type is dataclasses.InitVar
624 or type(a_type) is dataclasses.InitVar)
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400625
626
627def _is_type(annotation, cls, a_module, a_type, is_type_predicate):
628 # Given a type annotation string, does it refer to a_type in
629 # a_module? For example, when checking that annotation denotes a
630 # ClassVar, then a_module is typing, and a_type is
631 # typing.ClassVar.
632
633 # It's possible to look up a_module given a_type, but it involves
634 # looking in sys.modules (again!), and seems like a waste since
635 # the caller already knows a_module.
636
637 # - annotation is a string type annotation
638 # - cls is the class that this annotation was found in
639 # - a_module is the module we want to match
640 # - a_type is the type in that module we want to match
641 # - is_type_predicate is a function called with (obj, a_module)
642 # that determines if obj is of the desired type.
643
644 # Since this test does not do a local namespace lookup (and
645 # instead only a module (global) lookup), there are some things it
646 # gets wrong.
647
Eric V. Smithf8e75492018-05-16 05:14:53 -0400648 # With string annotations, cv0 will be detected as a ClassVar:
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400649 # CV = ClassVar
650 # @dataclass
651 # class C0:
652 # cv0: CV
653
Eric V. Smithf8e75492018-05-16 05:14:53 -0400654 # But in this example cv1 will not be detected as a ClassVar:
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400655 # @dataclass
656 # class C1:
657 # CV = ClassVar
658 # cv1: CV
659
Eric V. Smithf8e75492018-05-16 05:14:53 -0400660 # In C1, the code in this function (_is_type) will look up "CV" in
661 # the module and not find it, so it will not consider cv1 as a
662 # ClassVar. This is a fairly obscure corner case, and the best
663 # way to fix it would be to eval() the string "CV" with the
664 # correct global and local namespaces. However that would involve
665 # a eval() penalty for every single field of every dataclass
666 # that's defined. It was judged not worth it.
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400667
668 match = _MODULE_IDENTIFIER_RE.match(annotation)
669 if match:
670 ns = None
671 module_name = match.group(1)
672 if not module_name:
673 # No module name, assume the class's module did
674 # "from dataclasses import InitVar".
675 ns = sys.modules.get(cls.__module__).__dict__
676 else:
677 # Look up module_name in the class's module.
678 module = sys.modules.get(cls.__module__)
679 if module and module.__dict__.get(module_name) is a_module:
680 ns = sys.modules.get(a_type.__module__).__dict__
681 if ns and is_type_predicate(ns.get(match.group(2)), a_module):
682 return True
683 return False
684
685
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500686def _get_field(cls, a_name, a_type):
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400687 # Return a Field object for this field name and type. ClassVars
Eric V. Smithf8e75492018-05-16 05:14:53 -0400688 # and InitVars are also returned, but marked as such (see
689 # f._field_type).
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500690
Eric V. Smithf8e75492018-05-16 05:14:53 -0400691 # If the default value isn't derived from Field, then it's only a
692 # normal default value. Convert it to a Field().
Eric V. Smith03220fd2017-12-29 13:59:58 -0500693 default = getattr(cls, a_name, MISSING)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500694 if isinstance(default, Field):
695 f = default
696 else:
Eric V. Smith7389fd92018-03-19 21:07:51 -0400697 if isinstance(default, types.MemberDescriptorType):
698 # This is a field in __slots__, so it has no default value.
699 default = MISSING
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500700 f = field(default=default)
701
Eric V. Smithf8e75492018-05-16 05:14:53 -0400702 # Only at this point do we know the name and the type. Set them.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500703 f.name = a_name
704 f.type = a_type
705
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400706 # Assume it's a normal field until proven otherwise. We're next
Eric V. Smithf8e75492018-05-16 05:14:53 -0400707 # going to decide if it's a ClassVar or InitVar, everything else
708 # is just a normal field.
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400709 f._field_type = _FIELD
710
711 # In addition to checking for actual types here, also check for
Eric V. Smithf8e75492018-05-16 05:14:53 -0400712 # string annotations. get_type_hints() won't always work for us
713 # (see https://github.com/python/typing/issues/508 for example),
Eric V. Smith76beadb2021-04-17 09:53:24 -0400714 # plus it's expensive and would require an eval for every string
Eric V. Smithf8e75492018-05-16 05:14:53 -0400715 # annotation. So, make a best effort to see if this is a ClassVar
716 # or InitVar using regex's and checking that the thing referenced
717 # is actually of the correct type.
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400718
719 # For the complete discussion, see https://bugs.python.org/issue33453
720
721 # If typing has not been imported, then it's impossible for any
Eric V. Smithf8e75492018-05-16 05:14:53 -0400722 # annotation to be a ClassVar. So, only look for ClassVar if
723 # typing has been imported by any module (not necessarily cls's
724 # module).
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500725 typing = sys.modules.get('typing')
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400726 if typing:
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400727 if (_is_classvar(a_type, typing)
728 or (isinstance(f.type, str)
729 and _is_type(f.type, cls, typing, typing.ClassVar,
730 _is_classvar))):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500731 f._field_type = _FIELD_CLASSVAR
732
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400733 # If the type is InitVar, or if it's a matching string annotation,
734 # then it's an InitVar.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500735 if f._field_type is _FIELD:
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400736 # The module we're checking against is the module we're
737 # currently in (dataclasses.py).
738 dataclasses = sys.modules[__name__]
739 if (_is_initvar(a_type, dataclasses)
740 or (isinstance(f.type, str)
741 and _is_type(f.type, cls, dataclasses, dataclasses.InitVar,
742 _is_initvar))):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500743 f._field_type = _FIELD_INITVAR
744
Eric V. Smith2a7bacb2018-05-15 22:44:27 -0400745 # Validations for individual fields. This is delayed until now,
746 # instead of in the Field() constructor, since only here do we
747 # know the field name, which allows for better error reporting.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500748
749 # Special restrictions for ClassVar and InitVar.
750 if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR):
Eric V. Smith03220fd2017-12-29 13:59:58 -0500751 if f.default_factory is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500752 raise TypeError(f'field {f.name} cannot have a '
753 'default factory')
754 # Should I check for other field settings? default_factory
Eric V. Smithf8e75492018-05-16 05:14:53 -0400755 # seems the most serious to check for. Maybe add others. For
756 # example, how about init=False (or really,
757 # init=<not-the-default-init-value>)? It makes no sense for
758 # ClassVar and InitVar to specify init=<anything>.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500759
760 # For real fields, disallow mutable defaults for known types.
761 if f._field_type is _FIELD and isinstance(f.default, (list, dict, set)):
762 raise ValueError(f'mutable default {type(f.default)} for field '
763 f'{f.name} is not allowed: use default_factory')
764
765 return f
766
Batuhan Taskayac7437e22020-10-21 16:49:22 +0300767def _set_qualname(cls, value):
768 # Ensure that the functions returned from _create_fn uses the proper
769 # __qualname__ (the class they belong to).
770 if isinstance(value, FunctionType):
771 value.__qualname__ = f"{cls.__qualname__}.{value.__name__}"
772 return value
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500773
Eric V. Smithea8fc522018-01-27 19:07:40 -0500774def _set_new_attribute(cls, name, value):
775 # Never overwrites an existing attribute. Returns True if the
Eric V. Smithf8e75492018-05-16 05:14:53 -0400776 # attribute already exists.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500777 if name in cls.__dict__:
Eric V. Smithea8fc522018-01-27 19:07:40 -0500778 return True
Batuhan Taskayac7437e22020-10-21 16:49:22 +0300779 _set_qualname(cls, value)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500780 setattr(cls, name, value)
Eric V. Smithea8fc522018-01-27 19:07:40 -0500781 return False
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500782
783
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500784# Decide if/how we're going to create a hash function. Key is
Eric V. Smithf8e75492018-05-16 05:14:53 -0400785# (unsafe_hash, eq, frozen, does-hash-exist). Value is the action to
786# take. The common case is to do nothing, so instead of providing a
787# function that is a no-op, use None to signify that.
Eric V. Smith01d618c2018-03-24 22:10:14 -0400788
Yury Selivanovd219cc42019-12-09 09:54:20 -0500789def _hash_set_none(cls, fields, globals):
Eric V. Smith01d618c2018-03-24 22:10:14 -0400790 return None
791
Yury Selivanovd219cc42019-12-09 09:54:20 -0500792def _hash_add(cls, fields, globals):
Eric V. Smith01d618c2018-03-24 22:10:14 -0400793 flds = [f for f in fields if (f.compare if f.hash is None else f.hash)]
Batuhan Taskayac7437e22020-10-21 16:49:22 +0300794 return _set_qualname(cls, _hash_fn(flds, globals))
Eric V. Smith01d618c2018-03-24 22:10:14 -0400795
Yury Selivanovd219cc42019-12-09 09:54:20 -0500796def _hash_exception(cls, fields, globals):
Eric V. Smith01d618c2018-03-24 22:10:14 -0400797 # Raise an exception.
798 raise TypeError(f'Cannot overwrite attribute __hash__ '
799 f'in class {cls.__name__}')
800
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500801#
802# +-------------------------------------- unsafe_hash?
803# | +------------------------------- eq?
804# | | +------------------------ frozen?
805# | | | +---------------- has-explicit-hash?
806# | | | |
807# | | | | +------- action
808# | | | | |
809# v v v v v
Eric V. Smith01d618c2018-03-24 22:10:14 -0400810_hash_action = {(False, False, False, False): None,
811 (False, False, False, True ): None,
812 (False, False, True, False): None,
813 (False, False, True, True ): None,
814 (False, True, False, False): _hash_set_none,
815 (False, True, False, True ): None,
816 (False, True, True, False): _hash_add,
817 (False, True, True, True ): None,
818 (True, False, False, False): _hash_add,
819 (True, False, False, True ): _hash_exception,
820 (True, False, True, False): _hash_add,
821 (True, False, True, True ): _hash_exception,
822 (True, True, False, False): _hash_add,
823 (True, True, False, True ): _hash_exception,
824 (True, True, True, False): _hash_add,
825 (True, True, True, True ): _hash_exception,
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500826 }
827# See https://bugs.python.org/issue32929#msg312829 for an if-statement
Eric V. Smithf8e75492018-05-16 05:14:53 -0400828# version of this table.
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500829
830
Eric V. Smith750f4842021-04-10 21:28:42 -0400831def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen,
832 match_args):
Eric V. Smithd1388922018-01-07 14:30:17 -0500833 # Now that dicts retain insertion order, there's no reason to use
Eric V. Smithf8e75492018-05-16 05:14:53 -0400834 # an ordered dict. I am leveraging that ordering here, because
835 # derived class fields overwrite base class fields, but the order
836 # is defined by the base class, which is found first.
Eric V. Smithd1388922018-01-07 14:30:17 -0500837 fields = {}
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500838
Yury Selivanovd219cc42019-12-09 09:54:20 -0500839 if cls.__module__ in sys.modules:
840 globals = sys.modules[cls.__module__].__dict__
841 else:
842 # Theoretically this can happen if someone writes
843 # a custom string to cls.__module__. In which case
844 # such dataclass won't be fully introspectable
845 # (w.r.t. typing.get_type_hints) but will still function
846 # correctly.
847 globals = {}
848
Eric V. Smithf199bc62018-03-18 20:40:34 -0400849 setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order,
850 unsafe_hash, frozen))
851
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500852 # Find our base classes in reverse MRO order, and exclude
Eric V. Smithf8e75492018-05-16 05:14:53 -0400853 # ourselves. In reversed order so that more derived classes
854 # override earlier field definitions in base classes. As long as
855 # we're iterating over them, see if any are frozen.
Eric V. Smithf199bc62018-03-18 20:40:34 -0400856 any_frozen_base = False
857 has_dataclass_bases = False
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500858 for b in cls.__mro__[-1:0:-1]:
859 # Only process classes that have been processed by our
Eric V. Smithf8e75492018-05-16 05:14:53 -0400860 # decorator. That is, they have a _FIELDS attribute.
Eric V. Smithf199bc62018-03-18 20:40:34 -0400861 base_fields = getattr(b, _FIELDS, None)
Iurii Kemaev376ffc62021-04-06 06:14:01 +0100862 if base_fields is not None:
Eric V. Smithf199bc62018-03-18 20:40:34 -0400863 has_dataclass_bases = True
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500864 for f in base_fields.values():
865 fields[f.name] = f
Eric V. Smithf199bc62018-03-18 20:40:34 -0400866 if getattr(b, _PARAMS).frozen:
867 any_frozen_base = True
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500868
Eric V. Smith56970b82018-03-22 16:28:48 -0400869 # Annotations that are defined in this class (not in base
Eric V. Smithf8e75492018-05-16 05:14:53 -0400870 # classes). If __annotations__ isn't present, then this class
871 # adds no new annotations. We use this to compute fields that are
872 # added by this class.
873 #
Eric V. Smith56970b82018-03-22 16:28:48 -0400874 # Fields are found from cls_annotations, which is guaranteed to be
Eric V. Smithf8e75492018-05-16 05:14:53 -0400875 # ordered. Default values are from class attributes, if a field
876 # has a default. If the default value is a Field(), then it
877 # contains additional info beyond (and possibly including) the
878 # actual default value. Pseudo-fields ClassVars and InitVars are
879 # included, despite the fact that they're not real fields. That's
880 # dealt with later.
Eric V. Smith56970b82018-03-22 16:28:48 -0400881 cls_annotations = cls.__dict__.get('__annotations__', {})
882
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500883 # Now find fields in our class. While doing so, validate some
Eric V. Smithf8e75492018-05-16 05:14:53 -0400884 # things, and set the default values (as class attributes) where
885 # we can.
Eric V. Smith56970b82018-03-22 16:28:48 -0400886 cls_fields = [_get_field(cls, name, type)
887 for name, type in cls_annotations.items()]
888 for f in cls_fields:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500889 fields[f.name] = f
890
Eric V. Smithf8e75492018-05-16 05:14:53 -0400891 # If the class attribute (which is the default value for this
892 # field) exists and is of type 'Field', replace it with the
893 # real default. This is so that normal class introspection
894 # sees a real default value, not a Field.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500895 if isinstance(getattr(cls, f.name, None), Field):
Eric V. Smith03220fd2017-12-29 13:59:58 -0500896 if f.default is MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500897 # If there's no default, delete the class attribute.
Eric V. Smithf8e75492018-05-16 05:14:53 -0400898 # This happens if we specify field(repr=False), for
899 # example (that is, we specified a field object, but
900 # no default value). Also if we're using a default
901 # factory. The class attribute should not be set at
902 # all in the post-processed class.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500903 delattr(cls, f.name)
904 else:
905 setattr(cls, f.name, f.default)
906
Eric V. Smith56970b82018-03-22 16:28:48 -0400907 # Do we have any Field members that don't also have annotations?
908 for name, value in cls.__dict__.items():
909 if isinstance(value, Field) and not name in cls_annotations:
910 raise TypeError(f'{name!r} is a field but has no type annotation')
911
Eric V. Smithf199bc62018-03-18 20:40:34 -0400912 # Check rules that apply if we are derived from any dataclasses.
913 if has_dataclass_bases:
914 # Raise an exception if any of our bases are frozen, but we're not.
915 if any_frozen_base and not frozen:
916 raise TypeError('cannot inherit non-frozen dataclass from a '
917 'frozen one')
Eric V. Smith2fa6b9e2018-02-26 20:38:33 -0500918
Eric V. Smithf199bc62018-03-18 20:40:34 -0400919 # Raise an exception if we're frozen, but none of our bases are.
920 if not any_frozen_base and frozen:
921 raise TypeError('cannot inherit frozen dataclass from a '
922 'non-frozen one')
Eric V. Smith2fa6b9e2018-02-26 20:38:33 -0500923
Eric V. Smithf8e75492018-05-16 05:14:53 -0400924 # Remember all of the fields on our class (including bases). This
925 # also marks this class as being a dataclass.
Eric V. Smithf199bc62018-03-18 20:40:34 -0400926 setattr(cls, _FIELDS, fields)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500927
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500928 # Was this class defined with an explicit __hash__? Note that if
Eric V. Smithf8e75492018-05-16 05:14:53 -0400929 # __eq__ is defined in this class, then python will automatically
930 # set __hash__ to None. This is a heuristic, as it's possible
931 # that such a __hash__ == None was not auto-generated, but it
932 # close enough.
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500933 class_hash = cls.__dict__.get('__hash__', MISSING)
934 has_explicit_hash = not (class_hash is MISSING or
935 (class_hash is None and '__eq__' in cls.__dict__))
Eric V. Smithea8fc522018-01-27 19:07:40 -0500936
Eric V. Smithf8e75492018-05-16 05:14:53 -0400937 # If we're generating ordering methods, we must be generating the
938 # eq methods.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500939 if order and not eq:
940 raise ValueError('eq must be true if order is true')
941
942 if init:
943 # Does this class have a post-init function?
944 has_post_init = hasattr(cls, _POST_INIT_NAME)
945
946 # Include InitVars and regular fields (so, not ClassVars).
Eric V. Smithea8fc522018-01-27 19:07:40 -0500947 flds = [f for f in fields.values()
948 if f._field_type in (_FIELD, _FIELD_INITVAR)]
949 _set_new_attribute(cls, '__init__',
950 _init_fn(flds,
Eric V. Smith2fa6b9e2018-02-26 20:38:33 -0500951 frozen,
Eric V. Smithea8fc522018-01-27 19:07:40 -0500952 has_post_init,
Eric V. Smithf8e75492018-05-16 05:14:53 -0400953 # The name to use for the "self"
954 # param in __init__. Use "self"
955 # if possible.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500956 '__dataclass_self__' if 'self' in fields
957 else 'self',
Yury Selivanovd219cc42019-12-09 09:54:20 -0500958 globals,
Eric V. Smithea8fc522018-01-27 19:07:40 -0500959 ))
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500960
961 # Get the fields as a list, and include only real fields. This is
Eric V. Smithf8e75492018-05-16 05:14:53 -0400962 # used in all of the following methods.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500963 field_list = [f for f in fields.values() if f._field_type is _FIELD]
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500964
965 if repr:
Eric V. Smithea8fc522018-01-27 19:07:40 -0500966 flds = [f for f in field_list if f.repr]
Yury Selivanovd219cc42019-12-09 09:54:20 -0500967 _set_new_attribute(cls, '__repr__', _repr_fn(flds, globals))
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500968
969 if eq:
Eric V. Smithea8fc522018-01-27 19:07:40 -0500970 # Create _eq__ method. There's no need for a __ne__ method,
Eric V. Smithf8e75492018-05-16 05:14:53 -0400971 # since python will call __eq__ and negate it.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500972 flds = [f for f in field_list if f.compare]
973 self_tuple = _tuple_str('self', flds)
974 other_tuple = _tuple_str('other', flds)
975 _set_new_attribute(cls, '__eq__',
976 _cmp_fn('__eq__', '==',
Yury Selivanovd219cc42019-12-09 09:54:20 -0500977 self_tuple, other_tuple,
978 globals=globals))
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500979
980 if order:
Eric V. Smithea8fc522018-01-27 19:07:40 -0500981 # Create and set the ordering methods.
982 flds = [f for f in field_list if f.compare]
983 self_tuple = _tuple_str('self', flds)
984 other_tuple = _tuple_str('other', flds)
985 for name, op in [('__lt__', '<'),
986 ('__le__', '<='),
987 ('__gt__', '>'),
988 ('__ge__', '>='),
989 ]:
990 if _set_new_attribute(cls, name,
Yury Selivanovd219cc42019-12-09 09:54:20 -0500991 _cmp_fn(name, op, self_tuple, other_tuple,
992 globals=globals)):
Eric V. Smithea8fc522018-01-27 19:07:40 -0500993 raise TypeError(f'Cannot overwrite attribute {name} '
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500994 f'in class {cls.__name__}. Consider using '
Eric V. Smithea8fc522018-01-27 19:07:40 -0500995 'functools.total_ordering')
996
Eric V. Smith2fa6b9e2018-02-26 20:38:33 -0500997 if frozen:
Yury Selivanovd219cc42019-12-09 09:54:20 -0500998 for fn in _frozen_get_del_attr(cls, field_list, globals):
Eric V. Smithf199bc62018-03-18 20:40:34 -0400999 if _set_new_attribute(cls, fn.__name__, fn):
1000 raise TypeError(f'Cannot overwrite attribute {fn.__name__} '
Eric V. Smithdbf9cff2018-02-25 21:30:17 -05001001 f'in class {cls.__name__}')
Eric V. Smithea8fc522018-01-27 19:07:40 -05001002
1003 # Decide if/how we're going to create a hash function.
Eric V. Smithdbf9cff2018-02-25 21:30:17 -05001004 hash_action = _hash_action[bool(unsafe_hash),
1005 bool(eq),
1006 bool(frozen),
1007 has_explicit_hash]
Eric V. Smith01d618c2018-03-24 22:10:14 -04001008 if hash_action:
1009 # No need to call _set_new_attribute here, since by the time
Eric V. Smithf8e75492018-05-16 05:14:53 -04001010 # we're here the overwriting is unconditional.
Yury Selivanovd219cc42019-12-09 09:54:20 -05001011 cls.__hash__ = hash_action(cls, field_list, globals)
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001012
1013 if not getattr(cls, '__doc__'):
1014 # Create a class doc-string.
1015 cls.__doc__ = (cls.__name__ +
Pablo Galindob0544ba2021-04-21 12:41:19 +01001016 str(inspect.signature(cls)).replace(' -> None', ''))
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001017
Eric V. Smith750f4842021-04-10 21:28:42 -04001018 if match_args:
1019 _set_new_attribute(cls, '__match_args__',
1020 tuple(f.name for f in field_list if f.init))
Brandt Bucher145bf262021-02-26 14:51:55 -08001021
Ben Avrahamibef7d292020-10-06 20:40:50 +03001022 abc.update_abstractmethods(cls)
1023
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001024 return cls
1025
1026
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001027def dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False,
Eric V. Smith750f4842021-04-10 21:28:42 -04001028 unsafe_hash=False, frozen=False, match_args=True):
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001029 """Returns the same class as was passed in, with dunder methods
1030 added based on the fields defined in the class.
1031
1032 Examines PEP 526 __annotations__ to determine fields.
1033
1034 If init is true, an __init__() method is added to the class. If
1035 repr is true, a __repr__() method is added. If order is true, rich
Eric V. Smithdbf9cff2018-02-25 21:30:17 -05001036 comparison dunder methods are added. If unsafe_hash is true, a
1037 __hash__() method function is added. If frozen is true, fields may
Eric V. Smith750f4842021-04-10 21:28:42 -04001038 not be assigned to after instance creation. If match_args is true,
1039 the __match_args__ tuple is added.
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001040 """
1041
1042 def wrap(cls):
Eric V. Smith750f4842021-04-10 21:28:42 -04001043 return _process_class(cls, init, repr, eq, order, unsafe_hash,
1044 frozen, match_args)
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001045
1046 # See if we're being called as @dataclass or @dataclass().
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001047 if cls is None:
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001048 # We're called with parens.
1049 return wrap
1050
1051 # We're called as @dataclass without parens.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001052 return wrap(cls)
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001053
1054
1055def fields(class_or_instance):
1056 """Return a tuple describing the fields of this dataclass.
1057
1058 Accepts a dataclass or an instance of one. Tuple elements are of
1059 type Field.
1060 """
1061
1062 # Might it be worth caching this, per class?
1063 try:
Eric V. Smith2a7bacb2018-05-15 22:44:27 -04001064 fields = getattr(class_or_instance, _FIELDS)
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001065 except AttributeError:
1066 raise TypeError('must be called with a dataclass type or instance')
1067
Eric V. Smithd1388922018-01-07 14:30:17 -05001068 # Exclude pseudo-fields. Note that fields is sorted by insertion
Eric V. Smithf8e75492018-05-16 05:14:53 -04001069 # order, so the order of the tuple is as the fields were defined.
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001070 return tuple(f for f in fields.values() if f._field_type is _FIELD)
1071
1072
Eric V. Smithe7ba0132018-01-06 12:41:53 -05001073def _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001074 """Returns True if obj is an instance of a dataclass."""
Eric V. Smithb0f4dab2019-08-20 01:40:28 -04001075 return hasattr(type(obj), _FIELDS)
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001076
1077
Eric V. Smithe7ba0132018-01-06 12:41:53 -05001078def is_dataclass(obj):
1079 """Returns True if obj is a dataclass or an instance of a
1080 dataclass."""
Eric V. Smithb0f4dab2019-08-20 01:40:28 -04001081 cls = obj if isinstance(obj, type) else type(obj)
1082 return hasattr(cls, _FIELDS)
Eric V. Smithe7ba0132018-01-06 12:41:53 -05001083
1084
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001085def asdict(obj, *, dict_factory=dict):
1086 """Return the fields of a dataclass instance as a new dictionary mapping
1087 field names to field values.
1088
1089 Example usage:
1090
1091 @dataclass
1092 class C:
1093 x: int
1094 y: int
1095
1096 c = C(1, 2)
1097 assert asdict(c) == {'x': 1, 'y': 2}
1098
1099 If given, 'dict_factory' will be used instead of built-in dict.
1100 The function applies recursively to field values that are
1101 dataclass instances. This will also look into built-in containers:
1102 tuples, lists, and dicts.
1103 """
Eric V. Smithe7ba0132018-01-06 12:41:53 -05001104 if not _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001105 raise TypeError("asdict() should be called on dataclass instances")
1106 return _asdict_inner(obj, dict_factory)
1107
Eric V. Smithdbf9cff2018-02-25 21:30:17 -05001108
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001109def _asdict_inner(obj, dict_factory):
Eric V. Smithe7ba0132018-01-06 12:41:53 -05001110 if _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001111 result = []
1112 for f in fields(obj):
1113 value = _asdict_inner(getattr(obj, f.name), dict_factory)
1114 result.append((f.name, value))
1115 return dict_factory(result)
Eric V. Smith9b9d97d2018-09-14 11:32:16 -04001116 elif isinstance(obj, tuple) and hasattr(obj, '_fields'):
1117 # obj is a namedtuple. Recurse into it, but the returned
1118 # object is another namedtuple of the same type. This is
1119 # similar to how other list- or tuple-derived classes are
1120 # treated (see below), but we just need to create them
1121 # differently because a namedtuple's __init__ needs to be
1122 # called differently (see bpo-34363).
1123
1124 # I'm not using namedtuple's _asdict()
1125 # method, because:
1126 # - it does not recurse in to the namedtuple fields and
1127 # convert them to dicts (using dict_factory).
Jürgen Gmach80526f62020-06-24 12:46:52 +02001128 # - I don't actually want to return a dict here. The main
Eric V. Smith9b9d97d2018-09-14 11:32:16 -04001129 # use case here is json.dumps, and it handles converting
1130 # namedtuples to lists. Admittedly we're losing some
1131 # information here when we produce a json list instead of a
1132 # dict. Note that if we returned dicts here instead of
1133 # namedtuples, we could no longer call asdict() on a data
1134 # structure where a namedtuple was used as a dict key.
1135
1136 return type(obj)(*[_asdict_inner(v, dict_factory) for v in obj])
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001137 elif isinstance(obj, (list, tuple)):
Eric V. Smith9b9d97d2018-09-14 11:32:16 -04001138 # Assume we can create an object of this type by passing in a
1139 # generator (which is not true for namedtuples, handled
1140 # above).
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001141 return type(obj)(_asdict_inner(v, dict_factory) for v in obj)
1142 elif isinstance(obj, dict):
Eric V. Smith9b9d97d2018-09-14 11:32:16 -04001143 return type(obj)((_asdict_inner(k, dict_factory),
1144 _asdict_inner(v, dict_factory))
1145 for k, v in obj.items())
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001146 else:
Eric V. Smithf96ddad2018-03-24 17:20:26 -04001147 return copy.deepcopy(obj)
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001148
1149
1150def astuple(obj, *, tuple_factory=tuple):
1151 """Return the fields of a dataclass instance as a new tuple of field values.
1152
1153 Example usage::
1154
1155 @dataclass
1156 class C:
1157 x: int
1158 y: int
1159
1160 c = C(1, 2)
Raymond Hettingerd55209d2018-01-10 20:56:41 -08001161 assert astuple(c) == (1, 2)
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001162
1163 If given, 'tuple_factory' will be used instead of built-in tuple.
1164 The function applies recursively to field values that are
1165 dataclass instances. This will also look into built-in containers:
1166 tuples, lists, and dicts.
1167 """
1168
Eric V. Smithe7ba0132018-01-06 12:41:53 -05001169 if not _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001170 raise TypeError("astuple() should be called on dataclass instances")
1171 return _astuple_inner(obj, tuple_factory)
1172
Eric V. Smithdbf9cff2018-02-25 21:30:17 -05001173
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001174def _astuple_inner(obj, tuple_factory):
Eric V. Smithe7ba0132018-01-06 12:41:53 -05001175 if _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001176 result = []
1177 for f in fields(obj):
1178 value = _astuple_inner(getattr(obj, f.name), tuple_factory)
1179 result.append(value)
1180 return tuple_factory(result)
Eric V. Smith9b9d97d2018-09-14 11:32:16 -04001181 elif isinstance(obj, tuple) and hasattr(obj, '_fields'):
1182 # obj is a namedtuple. Recurse into it, but the returned
1183 # object is another namedtuple of the same type. This is
1184 # similar to how other list- or tuple-derived classes are
1185 # treated (see below), but we just need to create them
1186 # differently because a namedtuple's __init__ needs to be
1187 # called differently (see bpo-34363).
1188 return type(obj)(*[_astuple_inner(v, tuple_factory) for v in obj])
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001189 elif isinstance(obj, (list, tuple)):
Eric V. Smith9b9d97d2018-09-14 11:32:16 -04001190 # Assume we can create an object of this type by passing in a
1191 # generator (which is not true for namedtuples, handled
1192 # above).
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001193 return type(obj)(_astuple_inner(v, tuple_factory) for v in obj)
1194 elif isinstance(obj, dict):
1195 return type(obj)((_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory))
1196 for k, v in obj.items())
1197 else:
Eric V. Smithf96ddad2018-03-24 17:20:26 -04001198 return copy.deepcopy(obj)
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001199
1200
Eric V. Smithd80b4432018-01-06 17:09:58 -05001201def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
Eric V. Smith5da8cfb2018-03-01 08:01:41 -05001202 repr=True, eq=True, order=False, unsafe_hash=False,
Eric V. Smith750f4842021-04-10 21:28:42 -04001203 frozen=False, match_args=True):
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001204 """Return a new dynamically created dataclass.
1205
Eric V. Smithed7d4292018-01-06 16:14:03 -05001206 The dataclass name will be 'cls_name'. 'fields' is an iterable
1207 of either (name), (name, type) or (name, type, Field) objects. If type is
1208 omitted, use the string 'typing.Any'. Field objects are created by
Eric V. Smithd327ae62018-01-07 08:19:45 -05001209 the equivalent of calling 'field(name, type [, Field-info])'.
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001210
Raymond Hettingerd55209d2018-01-10 20:56:41 -08001211 C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,))
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001212
1213 is equivalent to:
1214
1215 @dataclass
1216 class C(Base):
Raymond Hettingerd55209d2018-01-10 20:56:41 -08001217 x: 'typing.Any'
1218 y: int
1219 z: int = field(init=False)
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001220
Raymond Hettingerd55209d2018-01-10 20:56:41 -08001221 For the bases and namespace parameters, see the builtin type() function.
Eric V. Smithd80b4432018-01-06 17:09:58 -05001222
Eric V. Smithdbf9cff2018-02-25 21:30:17 -05001223 The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to
Eric V. Smithd80b4432018-01-06 17:09:58 -05001224 dataclass().
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001225 """
1226
1227 if namespace is None:
1228 namespace = {}
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001229
Eric V. Smith4e812962018-05-16 11:31:29 -04001230 # While we're looking through the field names, validate that they
1231 # are identifiers, are not keywords, and not duplicates.
1232 seen = set()
Eric V. Smithc1a66bd2021-04-12 21:02:02 -04001233 annotations = {}
1234 defaults = {}
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001235 for item in fields:
Eric V. Smithed7d4292018-01-06 16:14:03 -05001236 if isinstance(item, str):
1237 name = item
1238 tp = 'typing.Any'
1239 elif len(item) == 2:
1240 name, tp, = item
1241 elif len(item) == 3:
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001242 name, tp, spec = item
Eric V. Smithc1a66bd2021-04-12 21:02:02 -04001243 defaults[name] = spec
Eric V. Smith4e812962018-05-16 11:31:29 -04001244 else:
1245 raise TypeError(f'Invalid field: {item!r}')
1246
1247 if not isinstance(name, str) or not name.isidentifier():
Min ho Kim96e12d52019-07-22 06:12:33 +10001248 raise TypeError(f'Field names must be valid identifiers: {name!r}')
Eric V. Smith4e812962018-05-16 11:31:29 -04001249 if keyword.iskeyword(name):
1250 raise TypeError(f'Field names must not be keywords: {name!r}')
1251 if name in seen:
1252 raise TypeError(f'Field name duplicated: {name!r}')
1253
1254 seen.add(name)
Eric V. Smithc1a66bd2021-04-12 21:02:02 -04001255 annotations[name] = tp
Eric V. Smithed7d4292018-01-06 16:14:03 -05001256
Eric V. Smithc1a66bd2021-04-12 21:02:02 -04001257 # Update 'ns' with the user-supplied namespace plus our calculated values.
1258 def exec_body_callback(ns):
1259 ns.update(namespace)
1260 ns.update(defaults)
1261 ns['__annotations__'] = annotations
1262
Ivan Levkivskyi5a7092d2018-03-31 13:41:17 +01001263 # We use `types.new_class()` instead of simply `type()` to allow dynamic creation
1264 # of generic dataclassses.
Eric V. Smithc1a66bd2021-04-12 21:02:02 -04001265 cls = types.new_class(cls_name, bases, {}, exec_body_callback)
1266
1267 # Apply the normal decorator.
Eric V. Smithd80b4432018-01-06 17:09:58 -05001268 return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
Eric V. Smith750f4842021-04-10 21:28:42 -04001269 unsafe_hash=unsafe_hash, frozen=frozen,
1270 match_args=match_args)
Eric V. Smithdbf9cff2018-02-25 21:30:17 -05001271
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001272
Serhiy Storchaka2d88e632019-06-26 19:07:44 +03001273def replace(obj, /, **changes):
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001274 """Return a new object replacing specified fields with new values.
1275
1276 This is especially useful for frozen classes. Example usage:
1277
1278 @dataclass(frozen=True)
1279 class C:
1280 x: int
1281 y: int
1282
1283 c = C(1, 2)
1284 c1 = replace(c, x=3)
1285 assert c1.x == 3 and c1.y == 2
1286 """
1287
Eric V. Smithf8e75492018-05-16 05:14:53 -04001288 # We're going to mutate 'changes', but that's okay because it's a
1289 # new dict, even if called with 'replace(obj, **my_changes)'.
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001290
Eric V. Smithe7ba0132018-01-06 12:41:53 -05001291 if not _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001292 raise TypeError("replace() should be called on dataclass instances")
1293
1294 # It's an error to have init=False fields in 'changes'.
1295 # If a field is not in 'changes', read its value from the provided obj.
1296
Eric V. Smithf199bc62018-03-18 20:40:34 -04001297 for f in getattr(obj, _FIELDS).values():
Eric V. Smithe7adf2b2018-06-07 14:43:59 -04001298 # Only consider normal fields or InitVars.
1299 if f._field_type is _FIELD_CLASSVAR:
1300 continue
1301
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001302 if not f.init:
1303 # Error if this field is specified in changes.
1304 if f.name in changes:
1305 raise ValueError(f'field {f.name} is declared with '
1306 'init=False, it cannot be specified with '
1307 'replace()')
1308 continue
1309
1310 if f.name not in changes:
Zackery Spytz75220672021-04-05 13:41:01 -06001311 if f._field_type is _FIELD_INITVAR and f.default is MISSING:
Dong-hee Na3d70f7a2018-06-23 23:46:32 +09001312 raise ValueError(f"InitVar {f.name!r} "
1313 'must be specified with replace()')
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001314 changes[f.name] = getattr(obj, f.name)
1315
Eric V. Smithf96ddad2018-03-24 17:20:26 -04001316 # Create the new object, which calls __init__() and
Eric V. Smithf8e75492018-05-16 05:14:53 -04001317 # __post_init__() (if defined), using all of the init fields we've
1318 # added and/or left in 'changes'. If there are values supplied in
1319 # changes that aren't fields, this will correctly raise a
1320 # TypeError.
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001321 return obj.__class__(**changes)