blob: 0f9041604a5a5844221e46221cb37308bedd5a45 [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.
Eric V. Smith01abc6e2018-05-15 08:36:21 -0400169class _FIELD_BASE:
170 def __init__(self, name):
171 self.name = name
172 def __repr__(self):
173 return self.name
174_FIELD = _FIELD_BASE('_FIELD')
175_FIELD_CLASSVAR = _FIELD_BASE('_FIELD_CLASSVAR')
176_FIELD_INITVAR = _FIELD_BASE('_FIELD_INITVAR')
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500177
178# The name of an attribute on the class where we store the Field
179# objects. Also used to check if a class is a Data Class.
Eric V. Smithf199bc62018-03-18 20:40:34 -0400180_FIELDS = '__dataclass_fields__'
181
182# The name of an attribute on the class that stores the parameters to
183# @dataclass.
184_PARAMS = '__dataclass_params__'
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500185
186# The name of the function, that if it exists, is called at the end of
187# __init__.
188_POST_INIT_NAME = '__post_init__'
189
190
191class _InitVarMeta(type):
192 def __getitem__(self, params):
193 return self
194
195class InitVar(metaclass=_InitVarMeta):
196 pass
197
198
199# Instances of Field are only ever created from within this module,
200# and only from the field() function, although Field instances are
201# exposed externally as (conceptually) read-only objects.
202# name and type are filled in after the fact, not in __init__. They're
203# not known at the time this class is instantiated, but it's
204# convenient if they're available later.
Eric V. Smithf199bc62018-03-18 20:40:34 -0400205# When cls._FIELDS is filled in with a list of Field objects, the name
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500206# and type fields will have been populated.
207class Field:
208 __slots__ = ('name',
209 'type',
210 'default',
211 'default_factory',
212 'repr',
213 'hash',
214 'init',
215 'compare',
216 'metadata',
217 '_field_type', # Private: not to be used by user code.
218 )
219
220 def __init__(self, default, default_factory, init, repr, hash, compare,
221 metadata):
222 self.name = None
223 self.type = None
224 self.default = default
225 self.default_factory = default_factory
226 self.init = init
227 self.repr = repr
228 self.hash = hash
229 self.compare = compare
230 self.metadata = (_EMPTY_METADATA
231 if metadata is None or len(metadata) == 0 else
232 types.MappingProxyType(metadata))
233 self._field_type = None
234
235 def __repr__(self):
236 return ('Field('
237 f'name={self.name!r},'
Eric V. Smith2473eea2018-05-14 11:37:28 -0400238 f'type={self.type!r},'
239 f'default={self.default!r},'
240 f'default_factory={self.default_factory!r},'
241 f'init={self.init!r},'
242 f'repr={self.repr!r},'
243 f'hash={self.hash!r},'
244 f'compare={self.compare!r},'
Eric V. Smith01abc6e2018-05-15 08:36:21 -0400245 f'metadata={self.metadata!r},'
246 f'_field_type={self._field_type}'
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500247 ')')
248
Eric V. Smithde7a2f02018-03-26 13:29:16 -0400249 # This is used to support the PEP 487 __set_name__ protocol in the
250 # case where we're using a field that contains a descriptor as a
251 # defaul value. For details on __set_name__, see
252 # https://www.python.org/dev/peps/pep-0487/#implementation-details.
253 # Note that in _process_class, this Field object is overwritten with
254 # the default value, so the end result is a descriptor that had
255 # __set_name__ called on it at the right time.
256 def __set_name__(self, owner, name):
Eric V. Smith52199522018-03-29 11:07:48 -0400257 func = getattr(type(self.default), '__set_name__', None)
Eric V. Smithde7a2f02018-03-26 13:29:16 -0400258 if func:
259 # There is a __set_name__ method on the descriptor,
260 # call it.
Eric V. Smith52199522018-03-29 11:07:48 -0400261 func(self.default, owner, name)
Eric V. Smithde7a2f02018-03-26 13:29:16 -0400262
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500263
Eric V. Smithf199bc62018-03-18 20:40:34 -0400264class _DataclassParams:
265 __slots__ = ('init',
266 'repr',
267 'eq',
268 'order',
269 'unsafe_hash',
270 'frozen',
271 )
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400272
Eric V. Smithf199bc62018-03-18 20:40:34 -0400273 def __init__(self, init, repr, eq, order, unsafe_hash, frozen):
274 self.init = init
275 self.repr = repr
276 self.eq = eq
277 self.order = order
278 self.unsafe_hash = unsafe_hash
279 self.frozen = frozen
280
281 def __repr__(self):
282 return ('_DataclassParams('
Eric V. Smith30590422018-05-14 17:16:52 -0400283 f'init={self.init!r},'
284 f'repr={self.repr!r},'
285 f'eq={self.eq!r},'
286 f'order={self.order!r},'
287 f'unsafe_hash={self.unsafe_hash!r},'
288 f'frozen={self.frozen!r}'
Eric V. Smithf199bc62018-03-18 20:40:34 -0400289 ')')
290
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400291
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500292# This function is used instead of exposing Field creation directly,
293# so that a type checker can be told (via overloads) that this is a
294# function whose type depends on its parameters.
Eric V. Smith03220fd2017-12-29 13:59:58 -0500295def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True,
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500296 hash=None, compare=True, metadata=None):
297 """Return an object to identify dataclass fields.
298
299 default is the default value of the field. default_factory is a
300 0-argument function called to initialize a field's value. If init
301 is True, the field will be a parameter to the class's __init__()
302 function. If repr is True, the field will be included in the
303 object's repr(). If hash is True, the field will be included in
304 the object's hash(). If compare is True, the field will be used in
305 comparison functions. metadata, if specified, must be a mapping
306 which is stored but not otherwise examined by dataclass.
307
308 It is an error to specify both default and default_factory.
309 """
310
Eric V. Smith03220fd2017-12-29 13:59:58 -0500311 if default is not MISSING and default_factory is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500312 raise ValueError('cannot specify both default and default_factory')
313 return Field(default, default_factory, init, repr, hash, compare,
314 metadata)
315
316
317def _tuple_str(obj_name, fields):
318 # Return a string representing each field of obj_name as a tuple
319 # member. So, if fields is ['x', 'y'] and obj_name is "self",
320 # return "(self.x,self.y)".
321
322 # Special case for the 0-tuple.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500323 if not fields:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500324 return '()'
325 # Note the trailing comma, needed if this turns out to be a 1-tuple.
326 return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)'
327
328
Eric V. Smithea8fc522018-01-27 19:07:40 -0500329def _create_fn(name, args, body, *, globals=None, locals=None,
Eric V. Smith03220fd2017-12-29 13:59:58 -0500330 return_type=MISSING):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500331 # Note that we mutate locals when exec() is called. Caller beware!
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400332 # The only callers are internal to this module, so no worries
333 # about external callers.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500334 if locals is None:
335 locals = {}
336 return_annotation = ''
Eric V. Smith03220fd2017-12-29 13:59:58 -0500337 if return_type is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500338 locals['_return_type'] = return_type
339 return_annotation = '->_return_type'
340 args = ','.join(args)
341 body = '\n'.join(f' {b}' for b in body)
342
Eric V. Smithf199bc62018-03-18 20:40:34 -0400343 # Compute the text of the entire function.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500344 txt = f'def {name}({args}){return_annotation}:\n{body}'
345
346 exec(txt, globals, locals)
347 return locals[name]
348
349
350def _field_assign(frozen, name, value, self_name):
351 # If we're a frozen class, then assign to our fields in __init__
352 # via object.__setattr__. Otherwise, just use a simple
353 # assignment.
354 # self_name is what "self" is called in this function: don't
355 # hard-code "self", since that might be a field name.
356 if frozen:
357 return f'object.__setattr__({self_name},{name!r},{value})'
358 return f'{self_name}.{name}={value}'
359
360
361def _field_init(f, frozen, globals, self_name):
362 # Return the text of the line in the body of __init__ that will
363 # initialize this field.
364
365 default_name = f'_dflt_{f.name}'
Eric V. Smith03220fd2017-12-29 13:59:58 -0500366 if f.default_factory is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500367 if f.init:
368 # This field has a default factory. If a parameter is
369 # given, use it. If not, call the factory.
370 globals[default_name] = f.default_factory
371 value = (f'{default_name}() '
372 f'if {f.name} is _HAS_DEFAULT_FACTORY '
373 f'else {f.name}')
374 else:
375 # This is a field that's not in the __init__ params, but
376 # has a default factory function. It needs to be
377 # initialized here by calling the factory function,
378 # because there's no other way to initialize it.
379
380 # For a field initialized with a default=defaultvalue, the
381 # class dict just has the default value
382 # (cls.fieldname=defaultvalue). But that won't work for a
383 # default factory, the factory must be called in __init__
384 # and we must assign that to self.fieldname. We can't
385 # fall back to the class dict's value, both because it's
386 # not set, and because it might be different per-class
387 # (which, after all, is why we have a factory function!).
388
389 globals[default_name] = f.default_factory
390 value = f'{default_name}()'
391 else:
392 # No default factory.
393 if f.init:
Eric V. Smith03220fd2017-12-29 13:59:58 -0500394 if f.default is MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500395 # There's no default, just do an assignment.
396 value = f.name
Eric V. Smith03220fd2017-12-29 13:59:58 -0500397 elif f.default is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500398 globals[default_name] = f.default
399 value = f.name
400 else:
401 # This field does not need initialization. Signify that to
402 # the caller by returning None.
403 return None
404
405 # Only test this now, so that we can create variables for the
406 # default. However, return None to signify that we're not going
407 # to actually do the assignment statement for InitVars.
408 if f._field_type == _FIELD_INITVAR:
409 return None
410
411 # Now, actually generate the field assignment.
412 return _field_assign(frozen, f.name, value, self_name)
413
414
415def _init_param(f):
416 # Return the __init__ parameter string for this field.
417 # For example, the equivalent of 'x:int=3' (except instead of 'int',
418 # reference a variable set to int, and instead of '3', reference a
419 # variable set to 3).
Eric V. Smith03220fd2017-12-29 13:59:58 -0500420 if f.default is MISSING and f.default_factory is MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500421 # There's no default, and no default_factory, just
422 # output the variable name and type.
423 default = ''
Eric V. Smith03220fd2017-12-29 13:59:58 -0500424 elif f.default is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500425 # There's a default, this will be the name that's used to look it up.
426 default = f'=_dflt_{f.name}'
Eric V. Smith03220fd2017-12-29 13:59:58 -0500427 elif f.default_factory is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500428 # There's a factory function. Set a marker.
429 default = '=_HAS_DEFAULT_FACTORY'
430 return f'{f.name}:_type_{f.name}{default}'
431
432
433def _init_fn(fields, frozen, has_post_init, self_name):
434 # fields contains both real fields and InitVar pseudo-fields.
435
436 # Make sure we don't have fields without defaults following fields
437 # with defaults. This actually would be caught when exec-ing the
438 # function source code, but catching it here gives a better error
439 # message, and future-proofs us in case we build up the function
440 # using ast.
441 seen_default = False
442 for f in fields:
443 # Only consider fields in the __init__ call.
444 if f.init:
Eric V. Smith03220fd2017-12-29 13:59:58 -0500445 if not (f.default is MISSING and f.default_factory is MISSING):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500446 seen_default = True
447 elif seen_default:
448 raise TypeError(f'non-default argument {f.name!r} '
449 'follows default argument')
450
Eric V. Smith03220fd2017-12-29 13:59:58 -0500451 globals = {'MISSING': MISSING,
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500452 '_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY}
453
454 body_lines = []
455 for f in fields:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500456 line = _field_init(f, frozen, globals, self_name)
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400457 # line is None means that this field doesn't require
458 # initialization (it's a pseudo-field). Just skip it.
459 if line:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500460 body_lines.append(line)
461
462 # Does this class have a post-init function?
463 if has_post_init:
464 params_str = ','.join(f.name for f in fields
465 if f._field_type is _FIELD_INITVAR)
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400466 body_lines.append(f'{self_name}.{_POST_INIT_NAME}({params_str})')
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500467
468 # If no body lines, use 'pass'.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500469 if not body_lines:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500470 body_lines = ['pass']
471
472 locals = {f'_type_{f.name}': f.type for f in fields}
473 return _create_fn('__init__',
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400474 [self_name] + [_init_param(f) for f in fields if f.init],
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500475 body_lines,
476 locals=locals,
477 globals=globals,
478 return_type=None)
479
480
481def _repr_fn(fields):
482 return _create_fn('__repr__',
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400483 ('self',),
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500484 ['return self.__class__.__qualname__ + f"(' +
485 ', '.join([f"{f.name}={{self.{f.name}!r}}"
486 for f in fields]) +
487 ')"'])
488
489
Eric V. Smithf199bc62018-03-18 20:40:34 -0400490def _frozen_get_del_attr(cls, fields):
491 # XXX: globals is modified on the first call to _create_fn, then the
492 # modified version is used in the second call. Is this okay?
493 globals = {'cls': cls,
494 'FrozenInstanceError': FrozenInstanceError}
495 if fields:
496 fields_str = '(' + ','.join(repr(f.name) for f in fields) + ',)'
497 else:
498 # Special case for the zero-length tuple.
499 fields_str = '()'
500 return (_create_fn('__setattr__',
501 ('self', 'name', 'value'),
502 (f'if type(self) is cls or name in {fields_str}:',
503 ' raise FrozenInstanceError(f"cannot assign to field {name!r}")',
504 f'super(cls, self).__setattr__(name, value)'),
505 globals=globals),
506 _create_fn('__delattr__',
507 ('self', 'name'),
508 (f'if type(self) is cls or name in {fields_str}:',
509 ' raise FrozenInstanceError(f"cannot delete field {name!r}")',
510 f'super(cls, self).__delattr__(name)'),
511 globals=globals),
512 )
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500513
514
515def _cmp_fn(name, op, self_tuple, other_tuple):
516 # Create a comparison function. If the fields in the object are
517 # named 'x' and 'y', then self_tuple is the string
518 # '(self.x,self.y)' and other_tuple is the string
519 # '(other.x,other.y)'.
520
521 return _create_fn(name,
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400522 ('self', 'other'),
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500523 [ 'if other.__class__ is self.__class__:',
524 f' return {self_tuple}{op}{other_tuple}',
525 'return NotImplemented'])
526
527
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500528def _hash_fn(fields):
529 self_tuple = _tuple_str('self', fields)
530 return _create_fn('__hash__',
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400531 ('self',),
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500532 [f'return hash({self_tuple})'])
533
534
535def _get_field(cls, a_name, a_type):
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400536 # Return a Field object for this field name and type. ClassVars
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500537 # and InitVars are also returned, but marked as such (see
538 # f._field_type).
539
Eric V. Smith8e4560a2018-03-21 17:10:22 -0400540 # If the default value isn't derived from Field, then it's
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500541 # only a normal default value. Convert it to a Field().
Eric V. Smith03220fd2017-12-29 13:59:58 -0500542 default = getattr(cls, a_name, MISSING)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500543 if isinstance(default, Field):
544 f = default
545 else:
Eric V. Smith7389fd92018-03-19 21:07:51 -0400546 if isinstance(default, types.MemberDescriptorType):
547 # This is a field in __slots__, so it has no default value.
548 default = MISSING
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500549 f = field(default=default)
550
551 # Assume it's a normal field until proven otherwise.
552 f._field_type = _FIELD
553
554 # Only at this point do we know the name and the type. Set them.
555 f.name = a_name
556 f.type = a_type
557
558 # If typing has not been imported, then it's impossible for
559 # any annotation to be a ClassVar. So, only look for ClassVar
560 # if typing has been imported.
561 typing = sys.modules.get('typing')
562 if typing is not None:
563 # This test uses a typing internal class, but it's the best
564 # way to test if this is a ClassVar.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000565 if (type(a_type) is typing._GenericAlias and
566 a_type.__origin__ is typing.ClassVar):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500567 # This field is a ClassVar, so it's not a field.
568 f._field_type = _FIELD_CLASSVAR
569
570 if f._field_type is _FIELD:
571 # Check if this is an InitVar.
572 if a_type is InitVar:
573 # InitVars are not fields, either.
574 f._field_type = _FIELD_INITVAR
575
576 # Validations for fields. This is delayed until now, instead of
577 # in the Field() constructor, since only here do we know the field
578 # name, which allows better error reporting.
579
580 # Special restrictions for ClassVar and InitVar.
581 if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR):
Eric V. Smith03220fd2017-12-29 13:59:58 -0500582 if f.default_factory is not MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500583 raise TypeError(f'field {f.name} cannot have a '
584 'default factory')
585 # Should I check for other field settings? default_factory
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400586 # seems the most serious to check for. Maybe add others.
587 # For example, how about init=False (or really,
588 # init=<not-the-default-init-value>)? It makes no sense for
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500589 # ClassVar and InitVar to specify init=<anything>.
590
591 # For real fields, disallow mutable defaults for known types.
592 if f._field_type is _FIELD and isinstance(f.default, (list, dict, set)):
593 raise ValueError(f'mutable default {type(f.default)} for field '
594 f'{f.name} is not allowed: use default_factory')
595
596 return f
597
598
Eric V. Smithea8fc522018-01-27 19:07:40 -0500599def _set_new_attribute(cls, name, value):
600 # Never overwrites an existing attribute. Returns True if the
601 # attribute already exists.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500602 if name in cls.__dict__:
Eric V. Smithea8fc522018-01-27 19:07:40 -0500603 return True
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500604 setattr(cls, name, value)
Eric V. Smithea8fc522018-01-27 19:07:40 -0500605 return False
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500606
607
Eric V. Smith01d618c2018-03-24 22:10:14 -0400608
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500609# Decide if/how we're going to create a hash function. Key is
610# (unsafe_hash, eq, frozen, does-hash-exist). Value is the action to
Eric V. Smith01d618c2018-03-24 22:10:14 -0400611# take. The common case is to do nothing, so instead of providing a
612# function that is a no-op, use None to signify that.
613
614def _hash_set_none(cls, fields):
615 return None
616
617def _hash_add(cls, fields):
618 flds = [f for f in fields if (f.compare if f.hash is None else f.hash)]
619 return _hash_fn(flds)
620
621def _hash_exception(cls, fields):
622 # Raise an exception.
623 raise TypeError(f'Cannot overwrite attribute __hash__ '
624 f'in class {cls.__name__}')
625
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500626#
627# +-------------------------------------- unsafe_hash?
628# | +------------------------------- eq?
629# | | +------------------------ frozen?
630# | | | +---------------- has-explicit-hash?
631# | | | |
632# | | | | +------- action
633# | | | | |
634# v v v v v
Eric V. Smith01d618c2018-03-24 22:10:14 -0400635_hash_action = {(False, False, False, False): None,
636 (False, False, False, True ): None,
637 (False, False, True, False): None,
638 (False, False, True, True ): None,
639 (False, True, False, False): _hash_set_none,
640 (False, True, False, True ): None,
641 (False, True, True, False): _hash_add,
642 (False, True, True, True ): None,
643 (True, False, False, False): _hash_add,
644 (True, False, False, True ): _hash_exception,
645 (True, False, True, False): _hash_add,
646 (True, False, True, True ): _hash_exception,
647 (True, True, False, False): _hash_add,
648 (True, True, False, True ): _hash_exception,
649 (True, True, True, False): _hash_add,
650 (True, True, True, True ): _hash_exception,
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500651 }
652# See https://bugs.python.org/issue32929#msg312829 for an if-statement
653# version of this table.
654
655
Eric V. Smithf199bc62018-03-18 20:40:34 -0400656def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen):
Eric V. Smithd1388922018-01-07 14:30:17 -0500657 # Now that dicts retain insertion order, there's no reason to use
658 # an ordered dict. I am leveraging that ordering here, because
659 # derived class fields overwrite base class fields, but the order
660 # is defined by the base class, which is found first.
661 fields = {}
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500662
Eric V. Smithf199bc62018-03-18 20:40:34 -0400663 setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order,
664 unsafe_hash, frozen))
665
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500666 # Find our base classes in reverse MRO order, and exclude
667 # ourselves. In reversed order so that more derived classes
668 # override earlier field definitions in base classes.
Eric V. Smithf199bc62018-03-18 20:40:34 -0400669 # As long as we're iterating over them, see if any are frozen.
670 any_frozen_base = False
671 has_dataclass_bases = False
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500672 for b in cls.__mro__[-1:0:-1]:
673 # Only process classes that have been processed by our
Eric V. Smithf199bc62018-03-18 20:40:34 -0400674 # decorator. That is, they have a _FIELDS attribute.
675 base_fields = getattr(b, _FIELDS, None)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500676 if base_fields:
Eric V. Smithf199bc62018-03-18 20:40:34 -0400677 has_dataclass_bases = True
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500678 for f in base_fields.values():
679 fields[f.name] = f
Eric V. Smithf199bc62018-03-18 20:40:34 -0400680 if getattr(b, _PARAMS).frozen:
681 any_frozen_base = True
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500682
Eric V. Smith56970b82018-03-22 16:28:48 -0400683 # Annotations that are defined in this class (not in base
684 # classes). If __annotations__ isn't present, then this class
685 # adds no new annotations. We use this to compute fields that
686 # are added by this class.
687 # Fields are found from cls_annotations, which is guaranteed to be
688 # ordered. Default values are from class attributes, if a field
689 # has a default. If the default value is a Field(), then it
690 # contains additional info beyond (and possibly including) the
691 # actual default value. Pseudo-fields ClassVars and InitVars are
692 # included, despite the fact that they're not real fields.
693 # That's dealt with later.
694 cls_annotations = cls.__dict__.get('__annotations__', {})
695
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500696 # Now find fields in our class. While doing so, validate some
697 # things, and set the default values (as class attributes)
698 # where we can.
Eric V. Smith56970b82018-03-22 16:28:48 -0400699 cls_fields = [_get_field(cls, name, type)
700 for name, type in cls_annotations.items()]
701 for f in cls_fields:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500702 fields[f.name] = f
703
704 # If the class attribute (which is the default value for
705 # this field) exists and is of type 'Field', replace it
706 # with the real default. This is so that normal class
707 # introspection sees a real default value, not a Field.
708 if isinstance(getattr(cls, f.name, None), Field):
Eric V. Smith03220fd2017-12-29 13:59:58 -0500709 if f.default is MISSING:
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500710 # If there's no default, delete the class attribute.
711 # This happens if we specify field(repr=False), for
712 # example (that is, we specified a field object, but
713 # no default value). Also if we're using a default
714 # factory. The class attribute should not be set at
715 # all in the post-processed class.
716 delattr(cls, f.name)
717 else:
718 setattr(cls, f.name, f.default)
719
Eric V. Smith56970b82018-03-22 16:28:48 -0400720 # Do we have any Field members that don't also have annotations?
721 for name, value in cls.__dict__.items():
722 if isinstance(value, Field) and not name in cls_annotations:
723 raise TypeError(f'{name!r} is a field but has no type annotation')
724
Eric V. Smithf199bc62018-03-18 20:40:34 -0400725 # Check rules that apply if we are derived from any dataclasses.
726 if has_dataclass_bases:
727 # Raise an exception if any of our bases are frozen, but we're not.
728 if any_frozen_base and not frozen:
729 raise TypeError('cannot inherit non-frozen dataclass from a '
730 'frozen one')
Eric V. Smith2fa6b9e2018-02-26 20:38:33 -0500731
Eric V. Smithf199bc62018-03-18 20:40:34 -0400732 # Raise an exception if we're frozen, but none of our bases are.
733 if not any_frozen_base and frozen:
734 raise TypeError('cannot inherit frozen dataclass from a '
735 'non-frozen one')
Eric V. Smith2fa6b9e2018-02-26 20:38:33 -0500736
Eric V. Smithf199bc62018-03-18 20:40:34 -0400737 # Remember all of the fields on our class (including bases). This also
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500738 # marks this class as being a dataclass.
Eric V. Smithf199bc62018-03-18 20:40:34 -0400739 setattr(cls, _FIELDS, fields)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500740
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500741 # Was this class defined with an explicit __hash__? Note that if
742 # __eq__ is defined in this class, then python will automatically
743 # set __hash__ to None. This is a heuristic, as it's possible
744 # that such a __hash__ == None was not auto-generated, but it
745 # close enough.
746 class_hash = cls.__dict__.get('__hash__', MISSING)
747 has_explicit_hash = not (class_hash is MISSING or
748 (class_hash is None and '__eq__' in cls.__dict__))
Eric V. Smithea8fc522018-01-27 19:07:40 -0500749
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500750 # If we're generating ordering methods, we must be generating
751 # the eq methods.
752 if order and not eq:
753 raise ValueError('eq must be true if order is true')
754
755 if init:
756 # Does this class have a post-init function?
757 has_post_init = hasattr(cls, _POST_INIT_NAME)
758
759 # Include InitVars and regular fields (so, not ClassVars).
Eric V. Smithea8fc522018-01-27 19:07:40 -0500760 flds = [f for f in fields.values()
761 if f._field_type in (_FIELD, _FIELD_INITVAR)]
762 _set_new_attribute(cls, '__init__',
763 _init_fn(flds,
Eric V. Smith2fa6b9e2018-02-26 20:38:33 -0500764 frozen,
Eric V. Smithea8fc522018-01-27 19:07:40 -0500765 has_post_init,
766 # The name to use for the "self" param
767 # in __init__. Use "self" if possible.
768 '__dataclass_self__' if 'self' in fields
769 else 'self',
770 ))
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500771
772 # Get the fields as a list, and include only real fields. This is
773 # used in all of the following methods.
Eric V. Smithea8fc522018-01-27 19:07:40 -0500774 field_list = [f for f in fields.values() if f._field_type is _FIELD]
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500775
776 if repr:
Eric V. Smithea8fc522018-01-27 19:07:40 -0500777 flds = [f for f in field_list if f.repr]
778 _set_new_attribute(cls, '__repr__', _repr_fn(flds))
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500779
780 if eq:
Eric V. Smithea8fc522018-01-27 19:07:40 -0500781 # Create _eq__ method. There's no need for a __ne__ method,
782 # since python will call __eq__ and negate it.
783 flds = [f for f in field_list if f.compare]
784 self_tuple = _tuple_str('self', flds)
785 other_tuple = _tuple_str('other', flds)
786 _set_new_attribute(cls, '__eq__',
787 _cmp_fn('__eq__', '==',
788 self_tuple, other_tuple))
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500789
790 if order:
Eric V. Smithea8fc522018-01-27 19:07:40 -0500791 # Create and set the ordering methods.
792 flds = [f for f in field_list if f.compare]
793 self_tuple = _tuple_str('self', flds)
794 other_tuple = _tuple_str('other', flds)
795 for name, op in [('__lt__', '<'),
796 ('__le__', '<='),
797 ('__gt__', '>'),
798 ('__ge__', '>='),
799 ]:
800 if _set_new_attribute(cls, name,
801 _cmp_fn(name, op, self_tuple, other_tuple)):
802 raise TypeError(f'Cannot overwrite attribute {name} '
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500803 f'in class {cls.__name__}. Consider using '
Eric V. Smithea8fc522018-01-27 19:07:40 -0500804 'functools.total_ordering')
805
Eric V. Smith2fa6b9e2018-02-26 20:38:33 -0500806 if frozen:
Eric V. Smithf199bc62018-03-18 20:40:34 -0400807 for fn in _frozen_get_del_attr(cls, field_list):
808 if _set_new_attribute(cls, fn.__name__, fn):
809 raise TypeError(f'Cannot overwrite attribute {fn.__name__} '
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500810 f'in class {cls.__name__}')
Eric V. Smithea8fc522018-01-27 19:07:40 -0500811
812 # Decide if/how we're going to create a hash function.
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500813 hash_action = _hash_action[bool(unsafe_hash),
814 bool(eq),
815 bool(frozen),
816 has_explicit_hash]
Eric V. Smith01d618c2018-03-24 22:10:14 -0400817 if hash_action:
818 # No need to call _set_new_attribute here, since by the time
819 # we're here the overwriting is unconditional.
820 cls.__hash__ = hash_action(cls, field_list)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500821
822 if not getattr(cls, '__doc__'):
823 # Create a class doc-string.
824 cls.__doc__ = (cls.__name__ +
825 str(inspect.signature(cls)).replace(' -> None', ''))
826
827 return cls
828
829
830# _cls should never be specified by keyword, so start it with an
Raymond Hettingerd55209d2018-01-10 20:56:41 -0800831# underscore. The presence of _cls is used to detect if this
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500832# decorator is being called with parameters or not.
833def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False,
Eric V. Smith5da8cfb2018-03-01 08:01:41 -0500834 unsafe_hash=False, frozen=False):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500835 """Returns the same class as was passed in, with dunder methods
836 added based on the fields defined in the class.
837
838 Examines PEP 526 __annotations__ to determine fields.
839
840 If init is true, an __init__() method is added to the class. If
841 repr is true, a __repr__() method is added. If order is true, rich
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500842 comparison dunder methods are added. If unsafe_hash is true, a
843 __hash__() method function is added. If frozen is true, fields may
844 not be assigned to after instance creation.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500845 """
846
847 def wrap(cls):
Eric V. Smithf199bc62018-03-18 20:40:34 -0400848 return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500849
850 # See if we're being called as @dataclass or @dataclass().
851 if _cls is None:
852 # We're called with parens.
853 return wrap
854
855 # We're called as @dataclass without parens.
856 return wrap(_cls)
857
858
859def fields(class_or_instance):
860 """Return a tuple describing the fields of this dataclass.
861
862 Accepts a dataclass or an instance of one. Tuple elements are of
863 type Field.
864 """
865
866 # Might it be worth caching this, per class?
867 try:
Eric V. Smithf199bc62018-03-18 20:40:34 -0400868 fields = getattr(class_or_instance, _FIELDS)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500869 except AttributeError:
870 raise TypeError('must be called with a dataclass type or instance')
871
Eric V. Smithd1388922018-01-07 14:30:17 -0500872 # Exclude pseudo-fields. Note that fields is sorted by insertion
873 # order, so the order of the tuple is as the fields were defined.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500874 return tuple(f for f in fields.values() if f._field_type is _FIELD)
875
876
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500877def _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500878 """Returns True if obj is an instance of a dataclass."""
Eric V. Smithf199bc62018-03-18 20:40:34 -0400879 return not isinstance(obj, type) and hasattr(obj, _FIELDS)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500880
881
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500882def is_dataclass(obj):
883 """Returns True if obj is a dataclass or an instance of a
884 dataclass."""
Eric V. Smithf199bc62018-03-18 20:40:34 -0400885 return hasattr(obj, _FIELDS)
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500886
887
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500888def asdict(obj, *, dict_factory=dict):
889 """Return the fields of a dataclass instance as a new dictionary mapping
890 field names to field values.
891
892 Example usage:
893
894 @dataclass
895 class C:
896 x: int
897 y: int
898
899 c = C(1, 2)
900 assert asdict(c) == {'x': 1, 'y': 2}
901
902 If given, 'dict_factory' will be used instead of built-in dict.
903 The function applies recursively to field values that are
904 dataclass instances. This will also look into built-in containers:
905 tuples, lists, and dicts.
906 """
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500907 if not _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500908 raise TypeError("asdict() should be called on dataclass instances")
909 return _asdict_inner(obj, dict_factory)
910
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500911
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500912def _asdict_inner(obj, dict_factory):
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500913 if _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500914 result = []
915 for f in fields(obj):
916 value = _asdict_inner(getattr(obj, f.name), dict_factory)
917 result.append((f.name, value))
918 return dict_factory(result)
919 elif isinstance(obj, (list, tuple)):
920 return type(obj)(_asdict_inner(v, dict_factory) for v in obj)
921 elif isinstance(obj, dict):
922 return type(obj)((_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory))
923 for k, v in obj.items())
924 else:
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400925 return copy.deepcopy(obj)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500926
927
928def astuple(obj, *, tuple_factory=tuple):
929 """Return the fields of a dataclass instance as a new tuple of field values.
930
931 Example usage::
932
933 @dataclass
934 class C:
935 x: int
936 y: int
937
938 c = C(1, 2)
Raymond Hettingerd55209d2018-01-10 20:56:41 -0800939 assert astuple(c) == (1, 2)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500940
941 If given, 'tuple_factory' will be used instead of built-in tuple.
942 The function applies recursively to field values that are
943 dataclass instances. This will also look into built-in containers:
944 tuples, lists, and dicts.
945 """
946
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500947 if not _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500948 raise TypeError("astuple() should be called on dataclass instances")
949 return _astuple_inner(obj, tuple_factory)
950
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500951
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500952def _astuple_inner(obj, tuple_factory):
Eric V. Smithe7ba0132018-01-06 12:41:53 -0500953 if _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500954 result = []
955 for f in fields(obj):
956 value = _astuple_inner(getattr(obj, f.name), tuple_factory)
957 result.append(value)
958 return tuple_factory(result)
959 elif isinstance(obj, (list, tuple)):
960 return type(obj)(_astuple_inner(v, tuple_factory) for v in obj)
961 elif isinstance(obj, dict):
962 return type(obj)((_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory))
963 for k, v in obj.items())
964 else:
Eric V. Smithf96ddad2018-03-24 17:20:26 -0400965 return copy.deepcopy(obj)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500966
967
Eric V. Smithd80b4432018-01-06 17:09:58 -0500968def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
Eric V. Smith5da8cfb2018-03-01 08:01:41 -0500969 repr=True, eq=True, order=False, unsafe_hash=False,
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500970 frozen=False):
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500971 """Return a new dynamically created dataclass.
972
Eric V. Smithed7d4292018-01-06 16:14:03 -0500973 The dataclass name will be 'cls_name'. 'fields' is an iterable
974 of either (name), (name, type) or (name, type, Field) objects. If type is
975 omitted, use the string 'typing.Any'. Field objects are created by
Eric V. Smithd327ae62018-01-07 08:19:45 -0500976 the equivalent of calling 'field(name, type [, Field-info])'.
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500977
Raymond Hettingerd55209d2018-01-10 20:56:41 -0800978 C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,))
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500979
980 is equivalent to:
981
982 @dataclass
983 class C(Base):
Raymond Hettingerd55209d2018-01-10 20:56:41 -0800984 x: 'typing.Any'
985 y: int
986 z: int = field(init=False)
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500987
Raymond Hettingerd55209d2018-01-10 20:56:41 -0800988 For the bases and namespace parameters, see the builtin type() function.
Eric V. Smithd80b4432018-01-06 17:09:58 -0500989
Eric V. Smithdbf9cff2018-02-25 21:30:17 -0500990 The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to
Eric V. Smithd80b4432018-01-06 17:09:58 -0500991 dataclass().
Eric V. Smithf0db54a2017-12-04 16:58:55 -0500992 """
993
994 if namespace is None:
995 namespace = {}
996 else:
997 # Copy namespace since we're going to mutate it.
998 namespace = namespace.copy()
999
Eric V. Smithd1388922018-01-07 14:30:17 -05001000 anns = {}
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001001 for item in fields:
Eric V. Smithed7d4292018-01-06 16:14:03 -05001002 if isinstance(item, str):
1003 name = item
1004 tp = 'typing.Any'
1005 elif len(item) == 2:
1006 name, tp, = item
1007 elif len(item) == 3:
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001008 name, tp, spec = item
1009 namespace[name] = spec
Eric V. Smithed7d4292018-01-06 16:14:03 -05001010 anns[name] = tp
1011
1012 namespace['__annotations__'] = anns
Ivan Levkivskyi5a7092d2018-03-31 13:41:17 +01001013 # We use `types.new_class()` instead of simply `type()` to allow dynamic creation
1014 # of generic dataclassses.
1015 cls = types.new_class(cls_name, bases, {}, lambda ns: ns.update(namespace))
Eric V. Smithd80b4432018-01-06 17:09:58 -05001016 return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
Eric V. Smithdbf9cff2018-02-25 21:30:17 -05001017 unsafe_hash=unsafe_hash, frozen=frozen)
1018
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001019
1020def replace(obj, **changes):
1021 """Return a new object replacing specified fields with new values.
1022
1023 This is especially useful for frozen classes. Example usage:
1024
1025 @dataclass(frozen=True)
1026 class C:
1027 x: int
1028 y: int
1029
1030 c = C(1, 2)
1031 c1 = replace(c, x=3)
1032 assert c1.x == 3 and c1.y == 2
1033 """
1034
1035 # We're going to mutate 'changes', but that's okay because it's a new
1036 # dict, even if called with 'replace(obj, **my_changes)'.
1037
Eric V. Smithe7ba0132018-01-06 12:41:53 -05001038 if not _is_dataclass_instance(obj):
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001039 raise TypeError("replace() should be called on dataclass instances")
1040
1041 # It's an error to have init=False fields in 'changes'.
1042 # If a field is not in 'changes', read its value from the provided obj.
1043
Eric V. Smithf199bc62018-03-18 20:40:34 -04001044 for f in getattr(obj, _FIELDS).values():
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001045 if not f.init:
1046 # Error if this field is specified in changes.
1047 if f.name in changes:
1048 raise ValueError(f'field {f.name} is declared with '
1049 'init=False, it cannot be specified with '
1050 'replace()')
1051 continue
1052
1053 if f.name not in changes:
1054 changes[f.name] = getattr(obj, f.name)
1055
Eric V. Smithf96ddad2018-03-24 17:20:26 -04001056 # Create the new object, which calls __init__() and
1057 # __post_init__() (if defined), using all of the init fields
1058 # we've added and/or left in 'changes'. If there are values
1059 # supplied in changes that aren't fields, this will correctly
1060 # raise a TypeError.
Eric V. Smithf0db54a2017-12-04 16:58:55 -05001061 return obj.__class__(**changes)