blob: 8ccc4c88aecab0dab9c20f12cffbb97ac9fa81e2 [file] [log] [blame]
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001import sys
Eric V. Smithf96ddad2018-03-24 17:20:26 -04002import copy
Eric V. Smithf0db54a2017-12-04 16:58:55 -05003import types
Eric V. Smithf0db54a2017-12-04 16:58:55 -05004import inspect
5
6__all__ = ['dataclass',
7 'field',
Eric V. Smith8e4560a2018-03-21 17:10:22 -04008 'Field',
Eric V. Smithf0db54a2017-12-04 16:58:55 -05009 'FrozenInstanceError',
10 'InitVar',
Eric V. Smith03220fd2017-12-29 13:59:58 -050011 'MISSING',
Eric V. Smithf0db54a2017-12-04 16:58:55 -050012
13 # Helper functions.
14 'fields',
15 'asdict',
16 'astuple',
17 'make_dataclass',
18 'replace',
Eric V. Smithe7ba0132018-01-06 12:41:53 -050019 'is_dataclass',
Eric V. Smithf0db54a2017-12-04 16:58:55 -050020 ]
21
Eric V. Smithea8fc522018-01-27 19:07:40 -050022# Conditions for adding methods. The boxes indicate what action the
23# dataclass decorator takes. For all of these tables, when I talk
Eric V. Smithdbf9cff2018-02-25 21:30:17 -050024# about init=, repr=, eq=, order=, unsafe_hash=, or frozen=, I'm
25# referring to the arguments to the @dataclass decorator. When
26# checking if a dunder method already exists, I mean check for an
27# entry in the class's __dict__. I never check to see if an
28# attribute is defined in a base class.
Eric V. Smithea8fc522018-01-27 19:07:40 -050029
30# Key:
31# +=========+=========================================+
32# + Value | Meaning |
33# +=========+=========================================+
34# | <blank> | No action: no method is added. |
35# +---------+-----------------------------------------+
36# | add | Generated method is added. |
37# +---------+-----------------------------------------+
Eric V. Smithea8fc522018-01-27 19:07:40 -050038# | raise | TypeError is raised. |
39# +---------+-----------------------------------------+
40# | None | Attribute is set to None. |
41# +=========+=========================================+
42
43# __init__
44#
45# +--- init= parameter
46# |
47# v | | |
48# | no | yes | <--- class has __init__ in __dict__?
49# +=======+=======+=======+
50# | False | | |
51# +-------+-------+-------+
52# | True | add | | <- the default
53# +=======+=======+=======+
54
55# __repr__
56#
57# +--- repr= parameter
58# |
59# v | | |
60# | no | yes | <--- class has __repr__ in __dict__?
61# +=======+=======+=======+
62# | False | | |
63# +-------+-------+-------+
64# | True | add | | <- the default
65# +=======+=======+=======+
66
67
68# __setattr__
69# __delattr__
70#
71# +--- frozen= parameter
72# |
73# v | | |
74# | no | yes | <--- class has __setattr__ or __delattr__ in __dict__?
75# +=======+=======+=======+
76# | False | | | <- the default
77# +-------+-------+-------+
78# | True | add | raise |
79# +=======+=======+=======+
80# Raise because not adding these methods would break the "frozen-ness"
81# of the class.
82
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
95# __lt__
96# __le__
97# __gt__
98# __ge__
99#
100# +--- order= parameter
101# |
102# v | | |
103# | no | yes | <--- class has any comparison method in __dict__?
104# +=======+=======+=======+
105# | False | | | <- the default
106# +-------+-------+-------+
107# | True | add | raise |
108# +=======+=======+=======+
109# Raise because to allow this case would interfere with using
110# functools.total_ordering.
111
112# __hash__
113
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500114# +------------------- unsafe_hash= parameter
115# | +----------- eq= parameter
116# | | +--- frozen= parameter
117# | | |
118# v v v | | |
119# | no | yes | <--- class has explicitly defined __hash__
120# +=======+=======+=======+========+========+
121# | False | False | False | | | No __eq__, use the base class __hash__
122# +-------+-------+-------+--------+--------+
123# | False | False | True | | | No __eq__, use the base class __hash__
124# +-------+-------+-------+--------+--------+
125# | False | True | False | None | | <-- the default, not hashable
126# +-------+-------+-------+--------+--------+
127# | False | True | True | add | | Frozen, so hashable, allows override
128# +-------+-------+-------+--------+--------+
129# | True | False | False | add | raise | Has no __eq__, but hashable
130# +-------+-------+-------+--------+--------+
131# | True | False | True | add | raise | Has no __eq__, but hashable
132# +-------+-------+-------+--------+--------+
133# | True | True | False | add | raise | Not frozen, but hashable
134# +-------+-------+-------+--------+--------+
135# | True | True | True | add | raise | Frozen, so hashable
136# +=======+=======+=======+========+========+
Eric V. Smithea8fc522018-01-27 19:07:40 -0500137# For boxes that are blank, __hash__ is untouched and therefore
138# inherited from the base class. If the base is object, then
139# id-based hashing is used.
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400140# Note that a class may already have __hash__=None if it specified an
Eric V. Smithea8fc522018-01-27 19:07:40 -0500141# __eq__ method in the class body (not one that was created by
142# @dataclass).
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500143# See _hash_action (below) for a coded version of this table.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500144
145
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500146# Raised when an attempt is made to modify a frozen class.
147class FrozenInstanceError(AttributeError): pass
148
149# A sentinel object for default values to signal that a
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400150# default factory will be used.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500151# This is given a nice repr() which will appear in the function
152# signature of dataclasses' constructors.
153class _HAS_DEFAULT_FACTORY_CLASS:
154 def __repr__(self):
155 return '<factory>'
156_HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS()
157
Eric V. Smith03220fd2017-12-29 13:59:58 -0500158# A sentinel object to detect if a parameter is supplied or not. Use
159# a class to give it a better repr.
160class _MISSING_TYPE:
161 pass
162MISSING = _MISSING_TYPE()
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500163
164# Since most per-field metadata will be unused, create an empty
165# read-only proxy that can be shared among all fields.
166_EMPTY_METADATA = types.MappingProxyType({})
167
168# Markers for the various kinds of fields and pseudo-fields.
169_FIELD = object() # An actual field.
170_FIELD_CLASSVAR = object() # Not a field, but a ClassVar.
171_FIELD_INITVAR = object() # Not a field, but an InitVar.
172
173# The name of an attribute on the class where we store the Field
174# objects. Also used to check if a class is a Data Class.
Eric V. Smithf199bc62018-03-18 20:40:34 -0400175_FIELDS = '__dataclass_fields__'
176
177# The name of an attribute on the class that stores the parameters to
178# @dataclass.
179_PARAMS = '__dataclass_params__'
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500180
181# The name of the function, that if it exists, is called at the end of
182# __init__.
183_POST_INIT_NAME = '__post_init__'
184
185
186class _InitVarMeta(type):
187 def __getitem__(self, params):
188 return self
189
190class InitVar(metaclass=_InitVarMeta):
191 pass
192
193
194# Instances of Field are only ever created from within this module,
195# and only from the field() function, although Field instances are
196# exposed externally as (conceptually) read-only objects.
197# name and type are filled in after the fact, not in __init__. They're
198# not known at the time this class is instantiated, but it's
199# convenient if they're available later.
Eric V. Smithf199bc62018-03-18 20:40:34 -0400200# When cls._FIELDS is filled in with a list of Field objects, the name
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500201# and type fields will have been populated.
202class Field:
203 __slots__ = ('name',
204 'type',
205 'default',
206 'default_factory',
207 'repr',
208 'hash',
209 'init',
210 'compare',
211 'metadata',
212 '_field_type', # Private: not to be used by user code.
213 )
214
215 def __init__(self, default, default_factory, init, repr, hash, compare,
216 metadata):
217 self.name = None
218 self.type = None
219 self.default = default
220 self.default_factory = default_factory
221 self.init = init
222 self.repr = repr
223 self.hash = hash
224 self.compare = compare
225 self.metadata = (_EMPTY_METADATA
226 if metadata is None or len(metadata) == 0 else
227 types.MappingProxyType(metadata))
228 self._field_type = None
229
230 def __repr__(self):
231 return ('Field('
232 f'name={self.name!r},'
233 f'type={self.type},'
234 f'default={self.default},'
235 f'default_factory={self.default_factory},'
236 f'init={self.init},'
237 f'repr={self.repr},'
238 f'hash={self.hash},'
239 f'compare={self.compare},'
240 f'metadata={self.metadata}'
241 ')')
242
243
Eric V. Smithf199bc62018-03-18 20:40:34 -0400244class _DataclassParams:
245 __slots__ = ('init',
246 'repr',
247 'eq',
248 'order',
249 'unsafe_hash',
250 'frozen',
251 )
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400252
Eric V. Smithf199bc62018-03-18 20:40:34 -0400253 def __init__(self, init, repr, eq, order, unsafe_hash, frozen):
254 self.init = init
255 self.repr = repr
256 self.eq = eq
257 self.order = order
258 self.unsafe_hash = unsafe_hash
259 self.frozen = frozen
260
261 def __repr__(self):
262 return ('_DataclassParams('
263 f'init={self.init},'
264 f'repr={self.repr},'
265 f'eq={self.eq},'
266 f'order={self.order},'
267 f'unsafe_hash={self.unsafe_hash},'
268 f'frozen={self.frozen}'
269 ')')
270
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400271
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500272# This function is used instead of exposing Field creation directly,
273# so that a type checker can be told (via overloads) that this is a
274# function whose type depends on its parameters.
Eric V. Smith03220fd2017-12-29 13:59:58 -0500275def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True,
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500276 hash=None, compare=True, metadata=None):
277 """Return an object to identify dataclass fields.
278
279 default is the default value of the field. default_factory is a
280 0-argument function called to initialize a field's value. If init
281 is True, the field will be a parameter to the class's __init__()
282 function. If repr is True, the field will be included in the
283 object's repr(). If hash is True, the field will be included in
284 the object's hash(). If compare is True, the field will be used in
285 comparison functions. metadata, if specified, must be a mapping
286 which is stored but not otherwise examined by dataclass.
287
288 It is an error to specify both default and default_factory.
289 """
290
Eric V. Smith03220fd2017-12-29 13:59:58 -0500291 if default is not MISSING and default_factory is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500292 raise ValueError('cannot specify both default and default_factory')
293 return Field(default, default_factory, init, repr, hash, compare,
294 metadata)
295
296
297def _tuple_str(obj_name, fields):
298 # Return a string representing each field of obj_name as a tuple
299 # member. So, if fields is ['x', 'y'] and obj_name is "self",
300 # return "(self.x,self.y)".
301
302 # Special case for the 0-tuple.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500303 if not fields:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500304 return '()'
305 # Note the trailing comma, needed if this turns out to be a 1-tuple.
306 return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)'
307
308
Eric V. Smithea8fc522018-01-27 19:07:40 -0500309def _create_fn(name, args, body, *, globals=None, locals=None,
Eric V. Smith03220fd2017-12-29 13:59:58 -0500310 return_type=MISSING):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500311 # Note that we mutate locals when exec() is called. Caller beware!
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400312 # The only callers are internal to this module, so no worries
313 # about external callers.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500314 if locals is None:
315 locals = {}
316 return_annotation = ''
Eric V. Smith03220fd2017-12-29 13:59:58 -0500317 if return_type is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500318 locals['_return_type'] = return_type
319 return_annotation = '->_return_type'
320 args = ','.join(args)
321 body = '\n'.join(f' {b}' for b in body)
322
Eric V. Smithf199bc62018-03-18 20:40:34 -0400323 # Compute the text of the entire function.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500324 txt = f'def {name}({args}){return_annotation}:\n{body}'
325
326 exec(txt, globals, locals)
327 return locals[name]
328
329
330def _field_assign(frozen, name, value, self_name):
331 # If we're a frozen class, then assign to our fields in __init__
332 # via object.__setattr__. Otherwise, just use a simple
333 # assignment.
334 # self_name is what "self" is called in this function: don't
335 # hard-code "self", since that might be a field name.
336 if frozen:
337 return f'object.__setattr__({self_name},{name!r},{value})'
338 return f'{self_name}.{name}={value}'
339
340
341def _field_init(f, frozen, globals, self_name):
342 # Return the text of the line in the body of __init__ that will
343 # initialize this field.
344
345 default_name = f'_dflt_{f.name}'
Eric V. Smith03220fd2017-12-29 13:59:58 -0500346 if f.default_factory is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500347 if f.init:
348 # This field has a default factory. If a parameter is
349 # given, use it. If not, call the factory.
350 globals[default_name] = f.default_factory
351 value = (f'{default_name}() '
352 f'if {f.name} is _HAS_DEFAULT_FACTORY '
353 f'else {f.name}')
354 else:
355 # This is a field that's not in the __init__ params, but
356 # has a default factory function. It needs to be
357 # initialized here by calling the factory function,
358 # because there's no other way to initialize it.
359
360 # For a field initialized with a default=defaultvalue, the
361 # class dict just has the default value
362 # (cls.fieldname=defaultvalue). But that won't work for a
363 # default factory, the factory must be called in __init__
364 # and we must assign that to self.fieldname. We can't
365 # fall back to the class dict's value, both because it's
366 # not set, and because it might be different per-class
367 # (which, after all, is why we have a factory function!).
368
369 globals[default_name] = f.default_factory
370 value = f'{default_name}()'
371 else:
372 # No default factory.
373 if f.init:
Eric V. Smith03220fd2017-12-29 13:59:58 -0500374 if f.default is MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500375 # There's no default, just do an assignment.
376 value = f.name
Eric V. Smith03220fd2017-12-29 13:59:58 -0500377 elif f.default is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500378 globals[default_name] = f.default
379 value = f.name
380 else:
381 # This field does not need initialization. Signify that to
382 # the caller by returning None.
383 return None
384
385 # Only test this now, so that we can create variables for the
386 # default. However, return None to signify that we're not going
387 # to actually do the assignment statement for InitVars.
388 if f._field_type == _FIELD_INITVAR:
389 return None
390
391 # Now, actually generate the field assignment.
392 return _field_assign(frozen, f.name, value, self_name)
393
394
395def _init_param(f):
396 # Return the __init__ parameter string for this field.
397 # For example, the equivalent of 'x:int=3' (except instead of 'int',
398 # reference a variable set to int, and instead of '3', reference a
399 # variable set to 3).
Eric V. Smith03220fd2017-12-29 13:59:58 -0500400 if f.default is MISSING and f.default_factory is MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500401 # There's no default, and no default_factory, just
402 # output the variable name and type.
403 default = ''
Eric V. Smith03220fd2017-12-29 13:59:58 -0500404 elif f.default is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500405 # There's a default, this will be the name that's used to look it up.
406 default = f'=_dflt_{f.name}'
Eric V. Smith03220fd2017-12-29 13:59:58 -0500407 elif f.default_factory is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500408 # There's a factory function. Set a marker.
409 default = '=_HAS_DEFAULT_FACTORY'
410 return f'{f.name}:_type_{f.name}{default}'
411
412
413def _init_fn(fields, frozen, has_post_init, self_name):
414 # fields contains both real fields and InitVar pseudo-fields.
415
416 # Make sure we don't have fields without defaults following fields
417 # with defaults. This actually would be caught when exec-ing the
418 # function source code, but catching it here gives a better error
419 # message, and future-proofs us in case we build up the function
420 # using ast.
421 seen_default = False
422 for f in fields:
423 # Only consider fields in the __init__ call.
424 if f.init:
Eric V. Smith03220fd2017-12-29 13:59:58 -0500425 if not (f.default is MISSING and f.default_factory is MISSING):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500426 seen_default = True
427 elif seen_default:
428 raise TypeError(f'non-default argument {f.name!r} '
429 'follows default argument')
430
Eric V. Smith03220fd2017-12-29 13:59:58 -0500431 globals = {'MISSING': MISSING,
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500432 '_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY}
433
434 body_lines = []
435 for f in fields:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500436 line = _field_init(f, frozen, globals, self_name)
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400437 # line is None means that this field doesn't require
438 # initialization (it's a pseudo-field). Just skip it.
439 if line:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500440 body_lines.append(line)
441
442 # Does this class have a post-init function?
443 if has_post_init:
444 params_str = ','.join(f.name for f in fields
445 if f._field_type is _FIELD_INITVAR)
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400446 body_lines.append(f'{self_name}.{_POST_INIT_NAME}({params_str})')
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500447
448 # If no body lines, use 'pass'.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500449 if not body_lines:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500450 body_lines = ['pass']
451
452 locals = {f'_type_{f.name}': f.type for f in fields}
453 return _create_fn('__init__',
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400454 [self_name] + [_init_param(f) for f in fields if f.init],
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500455 body_lines,
456 locals=locals,
457 globals=globals,
458 return_type=None)
459
460
461def _repr_fn(fields):
462 return _create_fn('__repr__',
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400463 ('self',),
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500464 ['return self.__class__.__qualname__ + f"(' +
465 ', '.join([f"{f.name}={{self.{f.name}!r}}"
466 for f in fields]) +
467 ')"'])
468
469
Eric V. Smithf199bc62018-03-18 20:40:34 -0400470def _frozen_get_del_attr(cls, fields):
471 # XXX: globals is modified on the first call to _create_fn, then the
472 # modified version is used in the second call. Is this okay?
473 globals = {'cls': cls,
474 'FrozenInstanceError': FrozenInstanceError}
475 if fields:
476 fields_str = '(' + ','.join(repr(f.name) for f in fields) + ',)'
477 else:
478 # Special case for the zero-length tuple.
479 fields_str = '()'
480 return (_create_fn('__setattr__',
481 ('self', 'name', 'value'),
482 (f'if type(self) is cls or name in {fields_str}:',
483 ' raise FrozenInstanceError(f"cannot assign to field {name!r}")',
484 f'super(cls, self).__setattr__(name, value)'),
485 globals=globals),
486 _create_fn('__delattr__',
487 ('self', 'name'),
488 (f'if type(self) is cls or name in {fields_str}:',
489 ' raise FrozenInstanceError(f"cannot delete field {name!r}")',
490 f'super(cls, self).__delattr__(name)'),
491 globals=globals),
492 )
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500493
494
495def _cmp_fn(name, op, self_tuple, other_tuple):
496 # Create a comparison function. If the fields in the object are
497 # named 'x' and 'y', then self_tuple is the string
498 # '(self.x,self.y)' and other_tuple is the string
499 # '(other.x,other.y)'.
500
501 return _create_fn(name,
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400502 ('self', 'other'),
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500503 [ 'if other.__class__ is self.__class__:',
504 f' return {self_tuple}{op}{other_tuple}',
505 'return NotImplemented'])
506
507
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500508def _hash_fn(fields):
509 self_tuple = _tuple_str('self', fields)
510 return _create_fn('__hash__',
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400511 ('self',),
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500512 [f'return hash({self_tuple})'])
513
514
515def _get_field(cls, a_name, a_type):
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400516 # Return a Field object for this field name and type. ClassVars
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500517 # and InitVars are also returned, but marked as such (see
518 # f._field_type).
519
Eric V. Smith8e4560a2018-03-21 17:10:22 -0400520 # If the default value isn't derived from Field, then it's
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500521 # only a normal default value. Convert it to a Field().
Eric V. Smith03220fd2017-12-29 13:59:58 -0500522 default = getattr(cls, a_name, MISSING)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500523 if isinstance(default, Field):
524 f = default
525 else:
Eric V. Smith7389fd92018-03-19 21:07:51 -0400526 if isinstance(default, types.MemberDescriptorType):
527 # This is a field in __slots__, so it has no default value.
528 default = MISSING
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500529 f = field(default=default)
530
531 # Assume it's a normal field until proven otherwise.
532 f._field_type = _FIELD
533
534 # Only at this point do we know the name and the type. Set them.
535 f.name = a_name
536 f.type = a_type
537
538 # If typing has not been imported, then it's impossible for
539 # any annotation to be a ClassVar. So, only look for ClassVar
540 # if typing has been imported.
541 typing = sys.modules.get('typing')
542 if typing is not None:
543 # This test uses a typing internal class, but it's the best
544 # way to test if this is a ClassVar.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000545 if (type(a_type) is typing._GenericAlias and
546 a_type.__origin__ is typing.ClassVar):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500547 # This field is a ClassVar, so it's not a field.
548 f._field_type = _FIELD_CLASSVAR
549
550 if f._field_type is _FIELD:
551 # Check if this is an InitVar.
552 if a_type is InitVar:
553 # InitVars are not fields, either.
554 f._field_type = _FIELD_INITVAR
555
556 # Validations for fields. This is delayed until now, instead of
557 # in the Field() constructor, since only here do we know the field
558 # name, which allows better error reporting.
559
560 # Special restrictions for ClassVar and InitVar.
561 if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR):
Eric V. Smith03220fd2017-12-29 13:59:58 -0500562 if f.default_factory is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500563 raise TypeError(f'field {f.name} cannot have a '
564 'default factory')
565 # Should I check for other field settings? default_factory
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400566 # seems the most serious to check for. Maybe add others.
567 # For example, how about init=False (or really,
568 # init=<not-the-default-init-value>)? It makes no sense for
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500569 # ClassVar and InitVar to specify init=<anything>.
570
571 # For real fields, disallow mutable defaults for known types.
572 if f._field_type is _FIELD and isinstance(f.default, (list, dict, set)):
573 raise ValueError(f'mutable default {type(f.default)} for field '
574 f'{f.name} is not allowed: use default_factory')
575
576 return f
577
578
Eric V. Smithea8fc522018-01-27 19:07:40 -0500579def _set_new_attribute(cls, name, value):
580 # Never overwrites an existing attribute. Returns True if the
581 # attribute already exists.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500582 if name in cls.__dict__:
Eric V. Smithea8fc522018-01-27 19:07:40 -0500583 return True
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500584 setattr(cls, name, value)
Eric V. Smithea8fc522018-01-27 19:07:40 -0500585 return False
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500586
587
Eric V. Smith01d618c2018-03-24 22:10:14 -0400588
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500589# Decide if/how we're going to create a hash function. Key is
590# (unsafe_hash, eq, frozen, does-hash-exist). Value is the action to
Eric V. Smith01d618c2018-03-24 22:10:14 -0400591# take. The common case is to do nothing, so instead of providing a
592# function that is a no-op, use None to signify that.
593
594def _hash_set_none(cls, fields):
595 return None
596
597def _hash_add(cls, fields):
598 flds = [f for f in fields if (f.compare if f.hash is None else f.hash)]
599 return _hash_fn(flds)
600
601def _hash_exception(cls, fields):
602 # Raise an exception.
603 raise TypeError(f'Cannot overwrite attribute __hash__ '
604 f'in class {cls.__name__}')
605
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500606#
607# +-------------------------------------- unsafe_hash?
608# | +------------------------------- eq?
609# | | +------------------------ frozen?
610# | | | +---------------- has-explicit-hash?
611# | | | |
612# | | | | +------- action
613# | | | | |
614# v v v v v
Eric V. Smith01d618c2018-03-24 22:10:14 -0400615_hash_action = {(False, False, False, False): None,
616 (False, False, False, True ): None,
617 (False, False, True, False): None,
618 (False, False, True, True ): None,
619 (False, True, False, False): _hash_set_none,
620 (False, True, False, True ): None,
621 (False, True, True, False): _hash_add,
622 (False, True, True, True ): None,
623 (True, False, False, False): _hash_add,
624 (True, False, False, True ): _hash_exception,
625 (True, False, True, False): _hash_add,
626 (True, False, True, True ): _hash_exception,
627 (True, True, False, False): _hash_add,
628 (True, True, False, True ): _hash_exception,
629 (True, True, True, False): _hash_add,
630 (True, True, True, True ): _hash_exception,
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500631 }
632# See https://bugs.python.org/issue32929#msg312829 for an if-statement
633# version of this table.
634
635
Eric V. Smithf199bc62018-03-18 20:40:34 -0400636def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
Eric V. Smithd1388922018-01-07 14:30:17 -0500637 # Now that dicts retain insertion order, there's no reason to use
638 # an ordered dict. I am leveraging that ordering here, because
639 # derived class fields overwrite base class fields, but the order
640 # is defined by the base class, which is found first.
641 fields = {}
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500642
Eric V. Smithf199bc62018-03-18 20:40:34 -0400643 setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order,
644 unsafe_hash, frozen))
645
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500646 # Find our base classes in reverse MRO order, and exclude
647 # ourselves. In reversed order so that more derived classes
648 # override earlier field definitions in base classes.
Eric V. Smithf199bc62018-03-18 20:40:34 -0400649 # As long as we're iterating over them, see if any are frozen.
650 any_frozen_base = False
651 has_dataclass_bases = False
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500652 for b in cls.__mro__[-1:0:-1]:
653 # Only process classes that have been processed by our
Eric V. Smithf199bc62018-03-18 20:40:34 -0400654 # decorator. That is, they have a _FIELDS attribute.
655 base_fields = getattr(b, _FIELDS, None)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500656 if base_fields:
Eric V. Smithf199bc62018-03-18 20:40:34 -0400657 has_dataclass_bases = True
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500658 for f in base_fields.values():
659 fields[f.name] = f
Eric V. Smithf199bc62018-03-18 20:40:34 -0400660 if getattr(b, _PARAMS).frozen:
661 any_frozen_base = True
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500662
Eric V. Smith56970b82018-03-22 16:28:48 -0400663 # Annotations that are defined in this class (not in base
664 # classes). If __annotations__ isn't present, then this class
665 # adds no new annotations. We use this to compute fields that
666 # are added by this class.
667 # Fields are found from cls_annotations, which is guaranteed to be
668 # ordered. Default values are from class attributes, if a field
669 # has a default. If the default value is a Field(), then it
670 # contains additional info beyond (and possibly including) the
671 # actual default value. Pseudo-fields ClassVars and InitVars are
672 # included, despite the fact that they're not real fields.
673 # That's dealt with later.
674 cls_annotations = cls.__dict__.get('__annotations__', {})
675
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500676 # Now find fields in our class. While doing so, validate some
677 # things, and set the default values (as class attributes)
678 # where we can.
Eric V. Smith56970b82018-03-22 16:28:48 -0400679 cls_fields = [_get_field(cls, name, type)
680 for name, type in cls_annotations.items()]
681 for f in cls_fields:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500682 fields[f.name] = f
683
684 # If the class attribute (which is the default value for
685 # this field) exists and is of type 'Field', replace it
686 # with the real default. This is so that normal class
687 # introspection sees a real default value, not a Field.
688 if isinstance(getattr(cls, f.name, None), Field):
Eric V. Smith03220fd2017-12-29 13:59:58 -0500689 if f.default is MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500690 # If there's no default, delete the class attribute.
691 # This happens if we specify field(repr=False), for
692 # example (that is, we specified a field object, but
693 # no default value). Also if we're using a default
694 # factory. The class attribute should not be set at
695 # all in the post-processed class.
696 delattr(cls, f.name)
697 else:
698 setattr(cls, f.name, f.default)
699
Eric V. Smith56970b82018-03-22 16:28:48 -0400700 # Do we have any Field members that don't also have annotations?
701 for name, value in cls.__dict__.items():
702 if isinstance(value, Field) and not name in cls_annotations:
703 raise TypeError(f'{name!r} is a field but has no type annotation')
704
Eric V. Smithf199bc62018-03-18 20:40:34 -0400705 # Check rules that apply if we are derived from any dataclasses.
706 if has_dataclass_bases:
707 # Raise an exception if any of our bases are frozen, but we're not.
708 if any_frozen_base and not frozen:
709 raise TypeError('cannot inherit non-frozen dataclass from a '
710 'frozen one')
Eric V. Smith2fa6b9e2018-02-26 20:38:33 -0500711
Eric V. Smithf199bc62018-03-18 20:40:34 -0400712 # Raise an exception if we're frozen, but none of our bases are.
713 if not any_frozen_base and frozen:
714 raise TypeError('cannot inherit frozen dataclass from a '
715 'non-frozen one')
Eric V. Smith2fa6b9e2018-02-26 20:38:33 -0500716
Eric V. Smithf199bc62018-03-18 20:40:34 -0400717 # Remember all of the fields on our class (including bases). This also
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500718 # marks this class as being a dataclass.
Eric V. Smithf199bc62018-03-18 20:40:34 -0400719 setattr(cls, _FIELDS, fields)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500720
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500721 # Was this class defined with an explicit __hash__? Note that if
722 # __eq__ is defined in this class, then python will automatically
723 # set __hash__ to None. This is a heuristic, as it's possible
724 # that such a __hash__ == None was not auto-generated, but it
725 # close enough.
726 class_hash = cls.__dict__.get('__hash__', MISSING)
727 has_explicit_hash = not (class_hash is MISSING or
728 (class_hash is None and '__eq__' in cls.__dict__))
Eric V. Smithea8fc522018-01-27 19:07:40 -0500729
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500730 # If we're generating ordering methods, we must be generating
731 # the eq methods.
732 if order and not eq:
733 raise ValueError('eq must be true if order is true')
734
735 if init:
736 # Does this class have a post-init function?
737 has_post_init = hasattr(cls, _POST_INIT_NAME)
738
739 # Include InitVars and regular fields (so, not ClassVars).
Eric V. Smithea8fc522018-01-27 19:07:40 -0500740 flds = [f for f in fields.values()
741 if f._field_type in (_FIELD, _FIELD_INITVAR)]
742 _set_new_attribute(cls, '__init__',
743 _init_fn(flds,
Eric V. Smith2fa6b9e2018-02-26 20:38:33 -0500744 frozen,
Eric V. Smithea8fc522018-01-27 19:07:40 -0500745 has_post_init,
746 # The name to use for the "self" param
747 # in __init__. Use "self" if possible.
748 '__dataclass_self__' if 'self' in fields
749 else 'self',
750 ))
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500751
752 # Get the fields as a list, and include only real fields. This is
753 # used in all of the following methods.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500754 field_list = [f for f in fields.values() if f._field_type is _FIELD]
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500755
756 if repr:
Eric V. Smithea8fc522018-01-27 19:07:40 -0500757 flds = [f for f in field_list if f.repr]
758 _set_new_attribute(cls, '__repr__', _repr_fn(flds))
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500759
760 if eq:
Eric V. Smithea8fc522018-01-27 19:07:40 -0500761 # Create _eq__ method. There's no need for a __ne__ method,
762 # since python will call __eq__ and negate it.
763 flds = [f for f in field_list if f.compare]
764 self_tuple = _tuple_str('self', flds)
765 other_tuple = _tuple_str('other', flds)
766 _set_new_attribute(cls, '__eq__',
767 _cmp_fn('__eq__', '==',
768 self_tuple, other_tuple))
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500769
770 if order:
Eric V. Smithea8fc522018-01-27 19:07:40 -0500771 # Create and set the ordering methods.
772 flds = [f for f in field_list if f.compare]
773 self_tuple = _tuple_str('self', flds)
774 other_tuple = _tuple_str('other', flds)
775 for name, op in [('__lt__', '<'),
776 ('__le__', '<='),
777 ('__gt__', '>'),
778 ('__ge__', '>='),
779 ]:
780 if _set_new_attribute(cls, name,
781 _cmp_fn(name, op, self_tuple, other_tuple)):
782 raise TypeError(f'Cannot overwrite attribute {name} '
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500783 f'in class {cls.__name__}. Consider using '
Eric V. Smithea8fc522018-01-27 19:07:40 -0500784 'functools.total_ordering')
785
Eric V. Smith2fa6b9e2018-02-26 20:38:33 -0500786 if frozen:
Eric V. Smithf199bc62018-03-18 20:40:34 -0400787 for fn in _frozen_get_del_attr(cls, field_list):
788 if _set_new_attribute(cls, fn.__name__, fn):
789 raise TypeError(f'Cannot overwrite attribute {fn.__name__} '
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500790 f'in class {cls.__name__}')
Eric V. Smithea8fc522018-01-27 19:07:40 -0500791
792 # Decide if/how we're going to create a hash function.
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500793 hash_action = _hash_action[bool(unsafe_hash),
794 bool(eq),
795 bool(frozen),
796 has_explicit_hash]
Eric V. Smith01d618c2018-03-24 22:10:14 -0400797 if hash_action:
798 # No need to call _set_new_attribute here, since by the time
799 # we're here the overwriting is unconditional.
800 cls.__hash__ = hash_action(cls, field_list)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500801
802 if not getattr(cls, '__doc__'):
803 # Create a class doc-string.
804 cls.__doc__ = (cls.__name__ +
805 str(inspect.signature(cls)).replace(' -> None', ''))
806
807 return cls
808
809
810# _cls should never be specified by keyword, so start it with an
Raymond Hettingerd55209d2018-01-10 20:56:41 -0800811# underscore. The presence of _cls is used to detect if this
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500812# decorator is being called with parameters or not.
813def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False,
Eric V. Smith5da8cfb2018-03-01 08:01:41 -0500814 unsafe_hash=False, frozen=False):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500815 """Returns the same class as was passed in, with dunder methods
816 added based on the fields defined in the class.
817
818 Examines PEP 526 __annotations__ to determine fields.
819
820 If init is true, an __init__() method is added to the class. If
821 repr is true, a __repr__() method is added. If order is true, rich
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500822 comparison dunder methods are added. If unsafe_hash is true, a
823 __hash__() method function is added. If frozen is true, fields may
824 not be assigned to after instance creation.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500825 """
826
827 def wrap(cls):
Eric V. Smithf199bc62018-03-18 20:40:34 -0400828 return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500829
830 # See if we're being called as @dataclass or @dataclass().
831 if _cls is None:
832 # We're called with parens.
833 return wrap
834
835 # We're called as @dataclass without parens.
836 return wrap(_cls)
837
838
839def fields(class_or_instance):
840 """Return a tuple describing the fields of this dataclass.
841
842 Accepts a dataclass or an instance of one. Tuple elements are of
843 type Field.
844 """
845
846 # Might it be worth caching this, per class?
847 try:
Eric V. Smithf199bc62018-03-18 20:40:34 -0400848 fields = getattr(class_or_instance, _FIELDS)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500849 except AttributeError:
850 raise TypeError('must be called with a dataclass type or instance')
851
Eric V. Smithd1388922018-01-07 14:30:17 -0500852 # Exclude pseudo-fields. Note that fields is sorted by insertion
853 # order, so the order of the tuple is as the fields were defined.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500854 return tuple(f for f in fields.values() if f._field_type is _FIELD)
855
856
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500857def _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500858 """Returns True if obj is an instance of a dataclass."""
Eric V. Smithf199bc62018-03-18 20:40:34 -0400859 return not isinstance(obj, type) and hasattr(obj, _FIELDS)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500860
861
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500862def is_dataclass(obj):
863 """Returns True if obj is a dataclass or an instance of a
864 dataclass."""
Eric V. Smithf199bc62018-03-18 20:40:34 -0400865 return hasattr(obj, _FIELDS)
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500866
867
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500868def asdict(obj, *, dict_factory=dict):
869 """Return the fields of a dataclass instance as a new dictionary mapping
870 field names to field values.
871
872 Example usage:
873
874 @dataclass
875 class C:
876 x: int
877 y: int
878
879 c = C(1, 2)
880 assert asdict(c) == {'x': 1, 'y': 2}
881
882 If given, 'dict_factory' will be used instead of built-in dict.
883 The function applies recursively to field values that are
884 dataclass instances. This will also look into built-in containers:
885 tuples, lists, and dicts.
886 """
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500887 if not _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500888 raise TypeError("asdict() should be called on dataclass instances")
889 return _asdict_inner(obj, dict_factory)
890
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500891
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500892def _asdict_inner(obj, dict_factory):
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500893 if _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500894 result = []
895 for f in fields(obj):
896 value = _asdict_inner(getattr(obj, f.name), dict_factory)
897 result.append((f.name, value))
898 return dict_factory(result)
899 elif isinstance(obj, (list, tuple)):
900 return type(obj)(_asdict_inner(v, dict_factory) for v in obj)
901 elif isinstance(obj, dict):
902 return type(obj)((_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory))
903 for k, v in obj.items())
904 else:
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400905 return copy.deepcopy(obj)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500906
907
908def astuple(obj, *, tuple_factory=tuple):
909 """Return the fields of a dataclass instance as a new tuple of field values.
910
911 Example usage::
912
913 @dataclass
914 class C:
915 x: int
916 y: int
917
918 c = C(1, 2)
Raymond Hettingerd55209d2018-01-10 20:56:41 -0800919 assert astuple(c) == (1, 2)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500920
921 If given, 'tuple_factory' will be used instead of built-in tuple.
922 The function applies recursively to field values that are
923 dataclass instances. This will also look into built-in containers:
924 tuples, lists, and dicts.
925 """
926
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500927 if not _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500928 raise TypeError("astuple() should be called on dataclass instances")
929 return _astuple_inner(obj, tuple_factory)
930
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500931
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500932def _astuple_inner(obj, tuple_factory):
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500933 if _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500934 result = []
935 for f in fields(obj):
936 value = _astuple_inner(getattr(obj, f.name), tuple_factory)
937 result.append(value)
938 return tuple_factory(result)
939 elif isinstance(obj, (list, tuple)):
940 return type(obj)(_astuple_inner(v, tuple_factory) for v in obj)
941 elif isinstance(obj, dict):
942 return type(obj)((_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory))
943 for k, v in obj.items())
944 else:
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400945 return copy.deepcopy(obj)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500946
947
Eric V. Smithd80b4432018-01-06 17:09:58 -0500948def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
Eric V. Smith5da8cfb2018-03-01 08:01:41 -0500949 repr=True, eq=True, order=False, unsafe_hash=False,
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500950 frozen=False):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500951 """Return a new dynamically created dataclass.
952
Eric V. Smithed7d4292018-01-06 16:14:03 -0500953 The dataclass name will be 'cls_name'. 'fields' is an iterable
954 of either (name), (name, type) or (name, type, Field) objects. If type is
955 omitted, use the string 'typing.Any'. Field objects are created by
Eric V. Smithd327ae62018-01-07 08:19:45 -0500956 the equivalent of calling 'field(name, type [, Field-info])'.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500957
Raymond Hettingerd55209d2018-01-10 20:56:41 -0800958 C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,))
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500959
960 is equivalent to:
961
962 @dataclass
963 class C(Base):
Raymond Hettingerd55209d2018-01-10 20:56:41 -0800964 x: 'typing.Any'
965 y: int
966 z: int = field(init=False)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500967
Raymond Hettingerd55209d2018-01-10 20:56:41 -0800968 For the bases and namespace parameters, see the builtin type() function.
Eric V. Smithd80b4432018-01-06 17:09:58 -0500969
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500970 The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to
Eric V. Smithd80b4432018-01-06 17:09:58 -0500971 dataclass().
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500972 """
973
974 if namespace is None:
975 namespace = {}
976 else:
977 # Copy namespace since we're going to mutate it.
978 namespace = namespace.copy()
979
Eric V. Smithd1388922018-01-07 14:30:17 -0500980 anns = {}
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500981 for item in fields:
Eric V. Smithed7d4292018-01-06 16:14:03 -0500982 if isinstance(item, str):
983 name = item
984 tp = 'typing.Any'
985 elif len(item) == 2:
986 name, tp, = item
987 elif len(item) == 3:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500988 name, tp, spec = item
989 namespace[name] = spec
Eric V. Smithed7d4292018-01-06 16:14:03 -0500990 anns[name] = tp
991
992 namespace['__annotations__'] = anns
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500993 cls = type(cls_name, bases, namespace)
Eric V. Smithd80b4432018-01-06 17:09:58 -0500994 return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500995 unsafe_hash=unsafe_hash, frozen=frozen)
996
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500997
998def replace(obj, **changes):
999 """Return a new object replacing specified fields with new values.
1000
1001 This is especially useful for frozen classes. Example usage:
1002
1003 @dataclass(frozen=True)
1004 class C:
1005 x: int
1006 y: int
1007
1008 c = C(1, 2)
1009 c1 = replace(c, x=3)
1010 assert c1.x == 3 and c1.y == 2
1011 """
1012
1013 # We're going to mutate 'changes', but that's okay because it's a new
1014 # dict, even if called with 'replace(obj, **my_changes)'.
1015
Eric V. Smithe7ba0132018-01-06 12:41:53 -05001016 if not _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001017 raise TypeError("replace() should be called on dataclass instances")
1018
1019 # It's an error to have init=False fields in 'changes'.
1020 # If a field is not in 'changes', read its value from the provided obj.
1021
Eric V. Smithf199bc62018-03-18 20:40:34 -04001022 for f in getattr(obj, _FIELDS).values():
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001023 if not f.init:
1024 # Error if this field is specified in changes.
1025 if f.name in changes:
1026 raise ValueError(f'field {f.name} is declared with '
1027 'init=False, it cannot be specified with '
1028 'replace()')
1029 continue
1030
1031 if f.name not in changes:
1032 changes[f.name] = getattr(obj, f.name)
1033
Eric V. Smithf96ddad2018-03-24 17:20:26 -04001034 # Create the new object, which calls __init__() and
1035 # __post_init__() (if defined), using all of the init fields
1036 # we've added and/or left in 'changes'. If there are values
1037 # supplied in changes that aren't fields, this will correctly
1038 # raise a TypeError.
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001039 return obj.__class__(**changes)