import re1import sys2import copy3import types4import inspect5import keyword6import functools7import itertools8import abc9import _thread10from types import FunctionType, GenericAlias111213__all__ = ['dataclass',14'field',15'Field',16'FrozenInstanceError',17'InitVar',18'KW_ONLY',19'MISSING',2021# Helper functions.22'fields',23'asdict',24'astuple',25'make_dataclass',26'replace',27'is_dataclass',28]2930# Conditions for adding methods. The boxes indicate what action the31# dataclass decorator takes. For all of these tables, when I talk32# about init=, repr=, eq=, order=, unsafe_hash=, or frozen=, I'm33# referring to the arguments to the @dataclass decorator. When34# checking if a dunder method already exists, I mean check for an35# entry in the class's __dict__. I never check to see if an attribute36# is defined in a base class.3738# Key:39# +=========+=========================================+40# + Value | Meaning |41# +=========+=========================================+42# | <blank> | No action: no method is added. |43# +---------+-----------------------------------------+44# | add | Generated method is added. |45# +---------+-----------------------------------------+46# | raise | TypeError is raised. |47# +---------+-----------------------------------------+48# | None | Attribute is set to None. |49# +=========+=========================================+5051# __init__52#53# +--- init= parameter54# |55# v | | |56# | no | yes | <--- class has __init__ in __dict__?57# +=======+=======+=======+58# | False | | |59# +-------+-------+-------+60# | True | add | | <- the default61# +=======+=======+=======+6263# __repr__64#65# +--- repr= parameter66# |67# v | | |68# | no | yes | <--- class has __repr__ in __dict__?69# +=======+=======+=======+70# | False | | |71# +-------+-------+-------+72# | True | add | | <- the default73# +=======+=======+=======+747576# __setattr__77# __delattr__78#79# +--- frozen= parameter80# |81# v | | |82# | no | yes | <--- class has __setattr__ or __delattr__ in __dict__?83# +=======+=======+=======+84# | False | | | <- the default85# +-------+-------+-------+86# | True | add | raise |87# +=======+=======+=======+88# Raise because not adding these methods would break the "frozen-ness"89# of the class.9091# __eq__92#93# +--- eq= parameter94# |95# v | | |96# | no | yes | <--- class has __eq__ in __dict__?97# +=======+=======+=======+98# | False | | |99# +-------+-------+-------+100# | True | add | | <- the default101# +=======+=======+=======+102103# __lt__104# __le__105# __gt__106# __ge__107#108# +--- order= parameter109# |110# v | | |111# | no | yes | <--- class has any comparison method in __dict__?112# +=======+=======+=======+113# | False | | | <- the default114# +-------+-------+-------+115# | True | add | raise |116# +=======+=======+=======+117# Raise because to allow this case would interfere with using118# functools.total_ordering.119120# __hash__121122# +------------------- unsafe_hash= parameter123# | +----------- eq= parameter124# | | +--- frozen= parameter125# | | |126# v v v | | |127# | no | yes | <--- class has explicitly defined __hash__128# +=======+=======+=======+========+========+129# | False | False | False | | | No __eq__, use the base class __hash__130# +-------+-------+-------+--------+--------+131# | False | False | True | | | No __eq__, use the base class __hash__132# +-------+-------+-------+--------+--------+133# | False | True | False | None | | <-- the default, not hashable134# +-------+-------+-------+--------+--------+135# | False | True | True | add | | Frozen, so hashable, allows override136# +-------+-------+-------+--------+--------+137# | True | False | False | add | raise | Has no __eq__, but hashable138# +-------+-------+-------+--------+--------+139# | True | False | True | add | raise | Has no __eq__, but hashable140# +-------+-------+-------+--------+--------+141# | True | True | False | add | raise | Not frozen, but hashable142# +-------+-------+-------+--------+--------+143# | True | True | True | add | raise | Frozen, so hashable144# +=======+=======+=======+========+========+145# For boxes that are blank, __hash__ is untouched and therefore146# inherited from the base class. If the base is object, then147# id-based hashing is used.148#149# Note that a class may already have __hash__=None if it specified an150# __eq__ method in the class body (not one that was created by151# @dataclass).152#153# See _hash_action (below) for a coded version of this table.154155# __match_args__156#157# +--- match_args= parameter158# |159# v | | |160# | no | yes | <--- class has __match_args__ in __dict__?161# +=======+=======+=======+162# | False | | |163# +-------+-------+-------+164# | True | add | | <- the default165# +=======+=======+=======+166# __match_args__ is always added unless the class already defines it. It is a167# tuple of __init__ parameter names; non-init fields must be matched by keyword.168169170# Raised when an attempt is made to modify a frozen class.171class FrozenInstanceError(AttributeError): pass172173# A sentinel object for default values to signal that a default174# factory will be used. This is given a nice repr() which will appear175# in the function signature of dataclasses' constructors.176class _HAS_DEFAULT_FACTORY_CLASS:177def __repr__(self):178return '<factory>'179_HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS()180181# A sentinel object to detect if a parameter is supplied or not. Use182# a class to give it a better repr.183class _MISSING_TYPE:184pass185MISSING = _MISSING_TYPE()186187# A sentinel object to indicate that following fields are keyword-only by188# default. Use a class to give it a better repr.189class _KW_ONLY_TYPE:190pass191KW_ONLY = _KW_ONLY_TYPE()192193# Since most per-field metadata will be unused, create an empty194# read-only proxy that can be shared among all fields.195_EMPTY_METADATA = types.MappingProxyType({})196197# Markers for the various kinds of fields and pseudo-fields.198class _FIELD_BASE:199def __init__(self, name):200self.name = name201def __repr__(self):202return self.name203_FIELD = _FIELD_BASE('_FIELD')204_FIELD_CLASSVAR = _FIELD_BASE('_FIELD_CLASSVAR')205_FIELD_INITVAR = _FIELD_BASE('_FIELD_INITVAR')206207# The name of an attribute on the class where we store the Field208# objects. Also used to check if a class is a Data Class.209_FIELDS = '__dataclass_fields__'210211# The name of an attribute on the class that stores the parameters to212# @dataclass.213_PARAMS = '__dataclass_params__'214215# The name of the function, that if it exists, is called at the end of216# __init__.217_POST_INIT_NAME = '__post_init__'218219# String regex that string annotations for ClassVar or InitVar must match.220# Allows "identifier.identifier[" or "identifier[".221# https://bugs.python.org/issue33453 for details.222_MODULE_IDENTIFIER_RE = re.compile(r'^(?:\s*(\w+)\s*\.)?\s*(\w+)')223224# Atomic immutable types which don't require any recursive handling and for which deepcopy225# returns the same object. We can provide a fast-path for these types in asdict and astuple.226_ATOMIC_TYPES = frozenset({227# Common JSON Serializable types228types.NoneType,229bool,230int,231float,232str,233# Other common types234complex,235bytes,236# Other types that are also unaffected by deepcopy237types.EllipsisType,238types.NotImplementedType,239types.CodeType,240types.BuiltinFunctionType,241types.FunctionType,242type,243range,244property,245})246247# This function's logic is copied from "recursive_repr" function in248# reprlib module to avoid dependency.249def _recursive_repr(user_function):250# Decorator to make a repr function return "..." for a recursive251# call.252repr_running = set()253254@functools.wraps(user_function)255def wrapper(self):256key = id(self), _thread.get_ident()257if key in repr_running:258return '...'259repr_running.add(key)260try:261result = user_function(self)262finally:263repr_running.discard(key)264return result265return wrapper266267class InitVar:268__slots__ = ('type', )269270def __init__(self, type):271self.type = type272273def __repr__(self):274if isinstance(self.type, type):275type_name = self.type.__name__276else:277# typing objects, e.g. List[int]278type_name = repr(self.type)279return f'dataclasses.InitVar[{type_name}]'280281def __class_getitem__(cls, type):282return InitVar(type)283284# Instances of Field are only ever created from within this module,285# and only from the field() function, although Field instances are286# exposed externally as (conceptually) read-only objects.287#288# name and type are filled in after the fact, not in __init__.289# They're not known at the time this class is instantiated, but it's290# convenient if they're available later.291#292# When cls._FIELDS is filled in with a list of Field objects, the name293# and type fields will have been populated.294class Field:295__slots__ = ('name',296'type',297'default',298'default_factory',299'repr',300'hash',301'init',302'compare',303'metadata',304'kw_only',305'_field_type', # Private: not to be used by user code.306)307308def __init__(self, default, default_factory, init, repr, hash, compare,309metadata, kw_only):310self.name = None311self.type = None312self.default = default313self.default_factory = default_factory314self.init = init315self.repr = repr316self.hash = hash317self.compare = compare318self.metadata = (_EMPTY_METADATA319if metadata is None else320types.MappingProxyType(metadata))321self.kw_only = kw_only322self._field_type = None323324@_recursive_repr325def __repr__(self):326return ('Field('327f'name={self.name!r},'328f'type={self.type!r},'329f'default={self.default!r},'330f'default_factory={self.default_factory!r},'331f'init={self.init!r},'332f'repr={self.repr!r},'333f'hash={self.hash!r},'334f'compare={self.compare!r},'335f'metadata={self.metadata!r},'336f'kw_only={self.kw_only!r},'337f'_field_type={self._field_type}'338')')339340# This is used to support the PEP 487 __set_name__ protocol in the341# case where we're using a field that contains a descriptor as a342# default value. For details on __set_name__, see343# https://peps.python.org/pep-0487/#implementation-details.344#345# Note that in _process_class, this Field object is overwritten346# with the default value, so the end result is a descriptor that347# had __set_name__ called on it at the right time.348def __set_name__(self, owner, name):349func = getattr(type(self.default), '__set_name__', None)350if func:351# There is a __set_name__ method on the descriptor, call352# it.353func(self.default, owner, name)354355__class_getitem__ = classmethod(GenericAlias)356357358class _DataclassParams:359__slots__ = ('init',360'repr',361'eq',362'order',363'unsafe_hash',364'frozen',365'match_args',366'kw_only',367'slots',368'weakref_slot',369)370371def __init__(self,372init, repr, eq, order, unsafe_hash, frozen,373match_args, kw_only, slots, weakref_slot):374self.init = init375self.repr = repr376self.eq = eq377self.order = order378self.unsafe_hash = unsafe_hash379self.frozen = frozen380self.match_args = match_args381self.kw_only = kw_only382self.slots = slots383self.weakref_slot = weakref_slot384385def __repr__(self):386return ('_DataclassParams('387f'init={self.init!r},'388f'repr={self.repr!r},'389f'eq={self.eq!r},'390f'order={self.order!r},'391f'unsafe_hash={self.unsafe_hash!r},'392f'frozen={self.frozen!r},'393f'match_args={self.match_args!r},'394f'kw_only={self.kw_only!r},'395f'slots={self.slots!r},'396f'weakref_slot={self.weakref_slot!r}'397')')398399400# This function is used instead of exposing Field creation directly,401# so that a type checker can be told (via overloads) that this is a402# function whose type depends on its parameters.403def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True,404hash=None, compare=True, metadata=None, kw_only=MISSING):405"""Return an object to identify dataclass fields.406407default is the default value of the field. default_factory is a4080-argument function called to initialize a field's value. If init409is true, the field will be a parameter to the class's __init__()410function. If repr is true, the field will be included in the411object's repr(). If hash is true, the field will be included in the412object's hash(). If compare is true, the field will be used in413comparison functions. metadata, if specified, must be a mapping414which is stored but not otherwise examined by dataclass. If kw_only415is true, the field will become a keyword-only parameter to416__init__().417418It is an error to specify both default and default_factory.419"""420421if default is not MISSING and default_factory is not MISSING:422raise ValueError('cannot specify both default and default_factory')423return Field(default, default_factory, init, repr, hash, compare,424metadata, kw_only)425426427def _fields_in_init_order(fields):428# Returns the fields as __init__ will output them. It returns 2 tuples:429# the first for normal args, and the second for keyword args.430431return (tuple(f for f in fields if f.init and not f.kw_only),432tuple(f for f in fields if f.init and f.kw_only)433)434435436def _tuple_str(obj_name, fields):437# Return a string representing each field of obj_name as a tuple438# member. So, if fields is ['x', 'y'] and obj_name is "self",439# return "(self.x,self.y)".440441# Special case for the 0-tuple.442if not fields:443return '()'444# Note the trailing comma, needed if this turns out to be a 1-tuple.445return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)'446447448def _create_fn(name, args, body, *, globals=None, locals=None,449return_type=MISSING):450# Note that we may mutate locals. Callers beware!451# The only callers are internal to this module, so no452# worries about external callers.453if locals is None:454locals = {}455return_annotation = ''456if return_type is not MISSING:457locals['__dataclass_return_type__'] = return_type458return_annotation = '->__dataclass_return_type__'459args = ','.join(args)460body = '\n'.join(f' {b}' for b in body)461462# Compute the text of the entire function.463txt = f' def {name}({args}){return_annotation}:\n{body}'464465# Free variables in exec are resolved in the global namespace.466# The global namespace we have is user-provided, so we can't modify it for467# our purposes. So we put the things we need into locals and introduce a468# scope to allow the function we're creating to close over them.469local_vars = ', '.join(locals.keys())470txt = f"def __create_fn__({local_vars}):\n{txt}\n return {name}"471ns = {}472exec(txt, globals, ns)473return ns['__create_fn__'](**locals)474475476def _field_assign(frozen, name, value, self_name):477# If we're a frozen class, then assign to our fields in __init__478# via object.__setattr__. Otherwise, just use a simple479# assignment.480#481# self_name is what "self" is called in this function: don't482# hard-code "self", since that might be a field name.483if frozen:484return f'__dataclass_builtins_object__.__setattr__({self_name},{name!r},{value})'485return f'{self_name}.{name}={value}'486487488def _field_init(f, frozen, globals, self_name, slots):489# Return the text of the line in the body of __init__ that will490# initialize this field.491492default_name = f'__dataclass_dflt_{f.name}__'493if f.default_factory is not MISSING:494if f.init:495# This field has a default factory. If a parameter is496# given, use it. If not, call the factory.497globals[default_name] = f.default_factory498value = (f'{default_name}() '499f'if {f.name} is __dataclass_HAS_DEFAULT_FACTORY__ '500f'else {f.name}')501else:502# This is a field that's not in the __init__ params, but503# has a default factory function. It needs to be504# initialized here by calling the factory function,505# because there's no other way to initialize it.506507# For a field initialized with a default=defaultvalue, the508# class dict just has the default value509# (cls.fieldname=defaultvalue). But that won't work for a510# default factory, the factory must be called in __init__511# and we must assign that to self.fieldname. We can't512# fall back to the class dict's value, both because it's513# not set, and because it might be different per-class514# (which, after all, is why we have a factory function!).515516globals[default_name] = f.default_factory517value = f'{default_name}()'518else:519# No default factory.520if f.init:521if f.default is MISSING:522# There's no default, just do an assignment.523value = f.name524elif f.default is not MISSING:525globals[default_name] = f.default526value = f.name527else:528# If the class has slots, then initialize this field.529if slots and f.default is not MISSING:530globals[default_name] = f.default531value = default_name532else:533# This field does not need initialization: reading from it will534# just use the class attribute that contains the default.535# Signify that to the caller by returning None.536return None537538# Only test this now, so that we can create variables for the539# default. However, return None to signify that we're not going540# to actually do the assignment statement for InitVars.541if f._field_type is _FIELD_INITVAR:542return None543544# Now, actually generate the field assignment.545return _field_assign(frozen, f.name, value, self_name)546547548def _init_param(f):549# Return the __init__ parameter string for this field. For550# example, the equivalent of 'x:int=3' (except instead of 'int',551# reference a variable set to int, and instead of '3', reference a552# variable set to 3).553if f.default is MISSING and f.default_factory is MISSING:554# There's no default, and no default_factory, just output the555# variable name and type.556default = ''557elif f.default is not MISSING:558# There's a default, this will be the name that's used to look559# it up.560default = f'=__dataclass_dflt_{f.name}__'561elif f.default_factory is not MISSING:562# There's a factory function. Set a marker.563default = '=__dataclass_HAS_DEFAULT_FACTORY__'564return f'{f.name}:__dataclass_type_{f.name}__{default}'565566567def _init_fn(fields, std_fields, kw_only_fields, frozen, has_post_init,568self_name, globals, slots):569# fields contains both real fields and InitVar pseudo-fields.570571# Make sure we don't have fields without defaults following fields572# with defaults. This actually would be caught when exec-ing the573# function source code, but catching it here gives a better error574# message, and future-proofs us in case we build up the function575# using ast.576577seen_default = False578for f in std_fields:579# Only consider the non-kw-only fields in the __init__ call.580if f.init:581if not (f.default is MISSING and f.default_factory is MISSING):582seen_default = True583elif seen_default:584raise TypeError(f'non-default argument {f.name!r} '585'follows default argument')586587locals = {f'__dataclass_type_{f.name}__': f.type for f in fields}588locals.update({589'__dataclass_HAS_DEFAULT_FACTORY__': _HAS_DEFAULT_FACTORY,590'__dataclass_builtins_object__': object,591})592593body_lines = []594for f in fields:595line = _field_init(f, frozen, locals, self_name, slots)596# line is None means that this field doesn't require597# initialization (it's a pseudo-field). Just skip it.598if line:599body_lines.append(line)600601# Does this class have a post-init function?602if has_post_init:603params_str = ','.join(f.name for f in fields604if f._field_type is _FIELD_INITVAR)605body_lines.append(f'{self_name}.{_POST_INIT_NAME}({params_str})')606607# If no body lines, use 'pass'.608if not body_lines:609body_lines = ['pass']610611_init_params = [_init_param(f) for f in std_fields]612if kw_only_fields:613# Add the keyword-only args. Because the * can only be added if614# there's at least one keyword-only arg, there needs to be a test here615# (instead of just concatenting the lists together).616_init_params += ['*']617_init_params += [_init_param(f) for f in kw_only_fields]618return _create_fn('__init__',619[self_name] + _init_params,620body_lines,621locals=locals,622globals=globals,623return_type=None)624625626def _repr_fn(fields, globals):627fn = _create_fn('__repr__',628('self',),629['return f"{self.__class__.__qualname__}(' +630', '.join([f"{f.name}={{self.{f.name}!r}}"631for f in fields]) +632')"'],633globals=globals)634return _recursive_repr(fn)635636637def _frozen_get_del_attr(cls, fields, globals):638locals = {'cls': cls,639'FrozenInstanceError': FrozenInstanceError}640condition = 'type(self) is cls'641if fields:642condition += ' or name in {' + ', '.join(repr(f.name) for f in fields) + '}'643return (_create_fn('__setattr__',644('self', 'name', 'value'),645(f'if {condition}:',646' raise FrozenInstanceError(f"cannot assign to field {name!r}")',647f'super(cls, self).__setattr__(name, value)'),648locals=locals,649globals=globals),650_create_fn('__delattr__',651('self', 'name'),652(f'if {condition}:',653' raise FrozenInstanceError(f"cannot delete field {name!r}")',654f'super(cls, self).__delattr__(name)'),655locals=locals,656globals=globals),657)658659660def _cmp_fn(name, op, self_tuple, other_tuple, globals):661# Create a comparison function. If the fields in the object are662# named 'x' and 'y', then self_tuple is the string663# '(self.x,self.y)' and other_tuple is the string664# '(other.x,other.y)'.665666return _create_fn(name,667('self', 'other'),668[ 'if other.__class__ is self.__class__:',669f' return {self_tuple}{op}{other_tuple}',670'return NotImplemented'],671globals=globals)672673674def _hash_fn(fields, globals):675self_tuple = _tuple_str('self', fields)676return _create_fn('__hash__',677('self',),678[f'return hash({self_tuple})'],679globals=globals)680681682def _is_classvar(a_type, typing):683# This test uses a typing internal class, but it's the best way to684# test if this is a ClassVar.685return (a_type is typing.ClassVar686or (type(a_type) is typing._GenericAlias687and a_type.__origin__ is typing.ClassVar))688689690def _is_initvar(a_type, dataclasses):691# The module we're checking against is the module we're692# currently in (dataclasses.py).693return (a_type is dataclasses.InitVar694or type(a_type) is dataclasses.InitVar)695696def _is_kw_only(a_type, dataclasses):697return a_type is dataclasses.KW_ONLY698699700def _is_type(annotation, cls, a_module, a_type, is_type_predicate):701# Given a type annotation string, does it refer to a_type in702# a_module? For example, when checking that annotation denotes a703# ClassVar, then a_module is typing, and a_type is704# typing.ClassVar.705706# It's possible to look up a_module given a_type, but it involves707# looking in sys.modules (again!), and seems like a waste since708# the caller already knows a_module.709710# - annotation is a string type annotation711# - cls is the class that this annotation was found in712# - a_module is the module we want to match713# - a_type is the type in that module we want to match714# - is_type_predicate is a function called with (obj, a_module)715# that determines if obj is of the desired type.716717# Since this test does not do a local namespace lookup (and718# instead only a module (global) lookup), there are some things it719# gets wrong.720721# With string annotations, cv0 will be detected as a ClassVar:722# CV = ClassVar723# @dataclass724# class C0:725# cv0: CV726727# But in this example cv1 will not be detected as a ClassVar:728# @dataclass729# class C1:730# CV = ClassVar731# cv1: CV732733# In C1, the code in this function (_is_type) will look up "CV" in734# the module and not find it, so it will not consider cv1 as a735# ClassVar. This is a fairly obscure corner case, and the best736# way to fix it would be to eval() the string "CV" with the737# correct global and local namespaces. However that would involve738# a eval() penalty for every single field of every dataclass739# that's defined. It was judged not worth it.740741match = _MODULE_IDENTIFIER_RE.match(annotation)742if match:743ns = None744module_name = match.group(1)745if not module_name:746# No module name, assume the class's module did747# "from dataclasses import InitVar".748ns = sys.modules.get(cls.__module__).__dict__749else:750# Look up module_name in the class's module.751module = sys.modules.get(cls.__module__)752if module and module.__dict__.get(module_name) is a_module:753ns = sys.modules.get(a_type.__module__).__dict__754if ns and is_type_predicate(ns.get(match.group(2)), a_module):755return True756return False757758759def _get_field(cls, a_name, a_type, default_kw_only):760# Return a Field object for this field name and type. ClassVars and761# InitVars are also returned, but marked as such (see f._field_type).762# default_kw_only is the value of kw_only to use if there isn't a field()763# that defines it.764765# If the default value isn't derived from Field, then it's only a766# normal default value. Convert it to a Field().767default = getattr(cls, a_name, MISSING)768if isinstance(default, Field):769f = default770else:771if isinstance(default, types.MemberDescriptorType):772# This is a field in __slots__, so it has no default value.773default = MISSING774f = field(default=default)775776# Only at this point do we know the name and the type. Set them.777f.name = a_name778f.type = a_type779780# Assume it's a normal field until proven otherwise. We're next781# going to decide if it's a ClassVar or InitVar, everything else782# is just a normal field.783f._field_type = _FIELD784785# In addition to checking for actual types here, also check for786# string annotations. get_type_hints() won't always work for us787# (see https://github.com/python/typing/issues/508 for example),788# plus it's expensive and would require an eval for every string789# annotation. So, make a best effort to see if this is a ClassVar790# or InitVar using regex's and checking that the thing referenced791# is actually of the correct type.792793# For the complete discussion, see https://bugs.python.org/issue33453794795# If typing has not been imported, then it's impossible for any796# annotation to be a ClassVar. So, only look for ClassVar if797# typing has been imported by any module (not necessarily cls's798# module).799typing = sys.modules.get('typing')800if typing:801if (_is_classvar(a_type, typing)802or (isinstance(f.type, str)803and _is_type(f.type, cls, typing, typing.ClassVar,804_is_classvar))):805f._field_type = _FIELD_CLASSVAR806807# If the type is InitVar, or if it's a matching string annotation,808# then it's an InitVar.809if f._field_type is _FIELD:810# The module we're checking against is the module we're811# currently in (dataclasses.py).812dataclasses = sys.modules[__name__]813if (_is_initvar(a_type, dataclasses)814or (isinstance(f.type, str)815and _is_type(f.type, cls, dataclasses, dataclasses.InitVar,816_is_initvar))):817f._field_type = _FIELD_INITVAR818819# Validations for individual fields. This is delayed until now,820# instead of in the Field() constructor, since only here do we821# know the field name, which allows for better error reporting.822823# Special restrictions for ClassVar and InitVar.824if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR):825if f.default_factory is not MISSING:826raise TypeError(f'field {f.name} cannot have a '827'default factory')828# Should I check for other field settings? default_factory829# seems the most serious to check for. Maybe add others. For830# example, how about init=False (or really,831# init=<not-the-default-init-value>)? It makes no sense for832# ClassVar and InitVar to specify init=<anything>.833834# kw_only validation and assignment.835if f._field_type in (_FIELD, _FIELD_INITVAR):836# For real and InitVar fields, if kw_only wasn't specified use the837# default value.838if f.kw_only is MISSING:839f.kw_only = default_kw_only840else:841# Make sure kw_only isn't set for ClassVars842assert f._field_type is _FIELD_CLASSVAR843if f.kw_only is not MISSING:844raise TypeError(f'field {f.name} is a ClassVar but specifies '845'kw_only')846847# For real fields, disallow mutable defaults. Use unhashable as a proxy848# indicator for mutability. Read the __hash__ attribute from the class,849# not the instance.850if f._field_type is _FIELD and f.default.__class__.__hash__ is None:851raise ValueError(f'mutable default {type(f.default)} for field '852f'{f.name} is not allowed: use default_factory')853854return f855856def _set_qualname(cls, value):857# Ensure that the functions returned from _create_fn uses the proper858# __qualname__ (the class they belong to).859if isinstance(value, FunctionType):860value.__qualname__ = f"{cls.__qualname__}.{value.__name__}"861return value862863def _set_new_attribute(cls, name, value):864# Never overwrites an existing attribute. Returns True if the865# attribute already exists.866if name in cls.__dict__:867return True868_set_qualname(cls, value)869setattr(cls, name, value)870return False871872873# Decide if/how we're going to create a hash function. Key is874# (unsafe_hash, eq, frozen, does-hash-exist). Value is the action to875# take. The common case is to do nothing, so instead of providing a876# function that is a no-op, use None to signify that.877878def _hash_set_none(cls, fields, globals):879return None880881def _hash_add(cls, fields, globals):882flds = [f for f in fields if (f.compare if f.hash is None else f.hash)]883return _set_qualname(cls, _hash_fn(flds, globals))884885def _hash_exception(cls, fields, globals):886# Raise an exception.887raise TypeError(f'Cannot overwrite attribute __hash__ '888f'in class {cls.__name__}')889890#891# +-------------------------------------- unsafe_hash?892# | +------------------------------- eq?893# | | +------------------------ frozen?894# | | | +---------------- has-explicit-hash?895# | | | |896# | | | | +------- action897# | | | | |898# v v v v v899_hash_action = {(False, False, False, False): None,900(False, False, False, True ): None,901(False, False, True, False): None,902(False, False, True, True ): None,903(False, True, False, False): _hash_set_none,904(False, True, False, True ): None,905(False, True, True, False): _hash_add,906(False, True, True, True ): None,907(True, False, False, False): _hash_add,908(True, False, False, True ): _hash_exception,909(True, False, True, False): _hash_add,910(True, False, True, True ): _hash_exception,911(True, True, False, False): _hash_add,912(True, True, False, True ): _hash_exception,913(True, True, True, False): _hash_add,914(True, True, True, True ): _hash_exception,915}916# See https://bugs.python.org/issue32929#msg312829 for an if-statement917# version of this table.918919920def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen,921match_args, kw_only, slots, weakref_slot):922# Now that dicts retain insertion order, there's no reason to use923# an ordered dict. I am leveraging that ordering here, because924# derived class fields overwrite base class fields, but the order925# is defined by the base class, which is found first.926fields = {}927928if cls.__module__ in sys.modules:929globals = sys.modules[cls.__module__].__dict__930else:931# Theoretically this can happen if someone writes932# a custom string to cls.__module__. In which case933# such dataclass won't be fully introspectable934# (w.r.t. typing.get_type_hints) but will still function935# correctly.936globals = {}937938setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order,939unsafe_hash, frozen,940match_args, kw_only,941slots, weakref_slot))942943# Find our base classes in reverse MRO order, and exclude944# ourselves. In reversed order so that more derived classes945# override earlier field definitions in base classes. As long as946# we're iterating over them, see if any are frozen.947any_frozen_base = False948has_dataclass_bases = False949for b in cls.__mro__[-1:0:-1]:950# Only process classes that have been processed by our951# decorator. That is, they have a _FIELDS attribute.952base_fields = getattr(b, _FIELDS, None)953if base_fields is not None:954has_dataclass_bases = True955for f in base_fields.values():956fields[f.name] = f957if getattr(b, _PARAMS).frozen:958any_frozen_base = True959960# Annotations defined specifically in this class (not in base classes).961#962# Fields are found from cls_annotations, which is guaranteed to be963# ordered. Default values are from class attributes, if a field964# has a default. If the default value is a Field(), then it965# contains additional info beyond (and possibly including) the966# actual default value. Pseudo-fields ClassVars and InitVars are967# included, despite the fact that they're not real fields. That's968# dealt with later.969cls_annotations = inspect.get_annotations(cls)970971# Now find fields in our class. While doing so, validate some972# things, and set the default values (as class attributes) where973# we can.974cls_fields = []975# Get a reference to this module for the _is_kw_only() test.976KW_ONLY_seen = False977dataclasses = sys.modules[__name__]978for name, type in cls_annotations.items():979# See if this is a marker to change the value of kw_only.980if (_is_kw_only(type, dataclasses)981or (isinstance(type, str)982and _is_type(type, cls, dataclasses, dataclasses.KW_ONLY,983_is_kw_only))):984# Switch the default to kw_only=True, and ignore this985# annotation: it's not a real field.986if KW_ONLY_seen:987raise TypeError(f'{name!r} is KW_ONLY, but KW_ONLY '988'has already been specified')989KW_ONLY_seen = True990kw_only = True991else:992# Otherwise it's a field of some type.993cls_fields.append(_get_field(cls, name, type, kw_only))994995for f in cls_fields:996fields[f.name] = f997998# If the class attribute (which is the default value for this999# field) exists and is of type 'Field', replace it with the1000# real default. This is so that normal class introspection1001# sees a real default value, not a Field.1002if isinstance(getattr(cls, f.name, None), Field):1003if f.default is MISSING:1004# If there's no default, delete the class attribute.1005# This happens if we specify field(repr=False), for1006# example (that is, we specified a field object, but1007# no default value). Also if we're using a default1008# factory. The class attribute should not be set at1009# all in the post-processed class.1010delattr(cls, f.name)1011else:1012setattr(cls, f.name, f.default)10131014# Do we have any Field members that don't also have annotations?1015for name, value in cls.__dict__.items():1016if isinstance(value, Field) and not name in cls_annotations:1017raise TypeError(f'{name!r} is a field but has no type annotation')10181019# Check rules that apply if we are derived from any dataclasses.1020if has_dataclass_bases:1021# Raise an exception if any of our bases are frozen, but we're not.1022if any_frozen_base and not frozen:1023raise TypeError('cannot inherit non-frozen dataclass from a '1024'frozen one')10251026# Raise an exception if we're frozen, but none of our bases are.1027if not any_frozen_base and frozen:1028raise TypeError('cannot inherit frozen dataclass from a '1029'non-frozen one')10301031# Remember all of the fields on our class (including bases). This1032# also marks this class as being a dataclass.1033setattr(cls, _FIELDS, fields)10341035# Was this class defined with an explicit __hash__? Note that if1036# __eq__ is defined in this class, then python will automatically1037# set __hash__ to None. This is a heuristic, as it's possible1038# that such a __hash__ == None was not auto-generated, but it1039# close enough.1040class_hash = cls.__dict__.get('__hash__', MISSING)1041has_explicit_hash = not (class_hash is MISSING or1042(class_hash is None and '__eq__' in cls.__dict__))10431044# If we're generating ordering methods, we must be generating the1045# eq methods.1046if order and not eq:1047raise ValueError('eq must be true if order is true')10481049# Include InitVars and regular fields (so, not ClassVars). This is1050# initialized here, outside of the "if init:" test, because std_init_fields1051# is used with match_args, below.1052all_init_fields = [f for f in fields.values()1053if f._field_type in (_FIELD, _FIELD_INITVAR)]1054(std_init_fields,1055kw_only_init_fields) = _fields_in_init_order(all_init_fields)10561057if init:1058# Does this class have a post-init function?1059has_post_init = hasattr(cls, _POST_INIT_NAME)10601061_set_new_attribute(cls, '__init__',1062_init_fn(all_init_fields,1063std_init_fields,1064kw_only_init_fields,1065frozen,1066has_post_init,1067# The name to use for the "self"1068# param in __init__. Use "self"1069# if possible.1070'__dataclass_self__' if 'self' in fields1071else 'self',1072globals,1073slots,1074))10751076# Get the fields as a list, and include only real fields. This is1077# used in all of the following methods.1078field_list = [f for f in fields.values() if f._field_type is _FIELD]10791080if repr:1081flds = [f for f in field_list if f.repr]1082_set_new_attribute(cls, '__repr__', _repr_fn(flds, globals))10831084if eq:1085# Create __eq__ method. There's no need for a __ne__ method,1086# since python will call __eq__ and negate it.1087cmp_fields = (field for field in field_list if field.compare)1088terms = [f'self.{field.name}==other.{field.name}' for field in cmp_fields]1089field_comparisons = ' and '.join(terms) or 'True'1090body = [f'if other.__class__ is self.__class__:',1091f' return {field_comparisons}',1092f'return NotImplemented']1093func = _create_fn('__eq__',1094('self', 'other'),1095body,1096globals=globals)1097_set_new_attribute(cls, '__eq__', func)10981099if order:1100# Create and set the ordering methods.1101flds = [f for f in field_list if f.compare]1102self_tuple = _tuple_str('self', flds)1103other_tuple = _tuple_str('other', flds)1104for name, op in [('__lt__', '<'),1105('__le__', '<='),1106('__gt__', '>'),1107('__ge__', '>='),1108]:1109if _set_new_attribute(cls, name,1110_cmp_fn(name, op, self_tuple, other_tuple,1111globals=globals)):1112raise TypeError(f'Cannot overwrite attribute {name} '1113f'in class {cls.__name__}. Consider using '1114'functools.total_ordering')11151116if frozen:1117for fn in _frozen_get_del_attr(cls, field_list, globals):1118if _set_new_attribute(cls, fn.__name__, fn):1119raise TypeError(f'Cannot overwrite attribute {fn.__name__} '1120f'in class {cls.__name__}')11211122# Decide if/how we're going to create a hash function.1123hash_action = _hash_action[bool(unsafe_hash),1124bool(eq),1125bool(frozen),1126has_explicit_hash]1127if hash_action:1128# No need to call _set_new_attribute here, since by the time1129# we're here the overwriting is unconditional.1130cls.__hash__ = hash_action(cls, field_list, globals)11311132if not getattr(cls, '__doc__'):1133# Create a class doc-string.1134try:1135# In some cases fetching a signature is not possible.1136# But, we surely should not fail in this case.1137text_sig = str(inspect.signature(cls)).replace(' -> None', '')1138except (TypeError, ValueError):1139text_sig = ''1140cls.__doc__ = (cls.__name__ + text_sig)11411142if match_args:1143# I could probably compute this once1144_set_new_attribute(cls, '__match_args__',1145tuple(f.name for f in std_init_fields))11461147# It's an error to specify weakref_slot if slots is False.1148if weakref_slot and not slots:1149raise TypeError('weakref_slot is True but slots is False')1150if slots:1151cls = _add_slots(cls, frozen, weakref_slot)11521153abc.update_abstractmethods(cls)11541155return cls115611571158# _dataclass_getstate and _dataclass_setstate are needed for pickling frozen1159# classes with slots. These could be slightly more performant if we generated1160# the code instead of iterating over fields. But that can be a project for1161# another day, if performance becomes an issue.1162def _dataclass_getstate(self):1163return [getattr(self, f.name) for f in fields(self)]116411651166def _dataclass_setstate(self, state):1167for field, value in zip(fields(self), state):1168# use setattr because dataclass may be frozen1169object.__setattr__(self, field.name, value)117011711172def _get_slots(cls):1173match cls.__dict__.get('__slots__'):1174case None:1175return1176case str(slot):1177yield slot1178# Slots may be any iterable, but we cannot handle an iterator1179# because it will already be (partially) consumed.1180case iterable if not hasattr(iterable, '__next__'):1181yield from iterable1182case _:1183raise TypeError(f"Slots of '{cls.__name__}' cannot be determined")118411851186def _add_slots(cls, is_frozen, weakref_slot):1187# Need to create a new class, since we can't set __slots__1188# after a class has been created.11891190# Make sure __slots__ isn't already set.1191if '__slots__' in cls.__dict__:1192raise TypeError(f'{cls.__name__} already specifies __slots__')11931194# Create a new dict for our new class.1195cls_dict = dict(cls.__dict__)1196field_names = tuple(f.name for f in fields(cls))1197# Make sure slots don't overlap with those in base classes.1198inherited_slots = set(1199itertools.chain.from_iterable(map(_get_slots, cls.__mro__[1:-1]))1200)1201# The slots for our class. Remove slots from our base classes. Add1202# '__weakref__' if weakref_slot was given, unless it is already present.1203cls_dict["__slots__"] = tuple(1204itertools.filterfalse(1205inherited_slots.__contains__,1206itertools.chain(1207# gh-93521: '__weakref__' also needs to be filtered out if1208# already present in inherited_slots1209field_names, ('__weakref__',) if weakref_slot else ()1210)1211),1212)12131214for field_name in field_names:1215# Remove our attributes, if present. They'll still be1216# available in _MARKER.1217cls_dict.pop(field_name, None)12181219# Remove __dict__ itself.1220cls_dict.pop('__dict__', None)12211222# Clear existing `__weakref__` descriptor, it belongs to a previous type:1223cls_dict.pop('__weakref__', None) # gh-10206912241225# And finally create the class.1226qualname = getattr(cls, '__qualname__', None)1227cls = type(cls)(cls.__name__, cls.__bases__, cls_dict)1228if qualname is not None:1229cls.__qualname__ = qualname12301231if is_frozen:1232# Need this for pickling frozen classes with slots.1233if '__getstate__' not in cls_dict:1234cls.__getstate__ = _dataclass_getstate1235if '__setstate__' not in cls_dict:1236cls.__setstate__ = _dataclass_setstate12371238return cls123912401241def dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False,1242unsafe_hash=False, frozen=False, match_args=True,1243kw_only=False, slots=False, weakref_slot=False):1244"""Add dunder methods based on the fields defined in the class.12451246Examines PEP 526 __annotations__ to determine fields.12471248If init is true, an __init__() method is added to the class. If repr1249is true, a __repr__() method is added. If order is true, rich1250comparison dunder methods are added. If unsafe_hash is true, a1251__hash__() method is added. If frozen is true, fields may not be1252assigned to after instance creation. If match_args is true, the1253__match_args__ tuple is added. If kw_only is true, then by default1254all fields are keyword-only. If slots is true, a new class with a1255__slots__ attribute is returned.1256"""12571258def wrap(cls):1259return _process_class(cls, init, repr, eq, order, unsafe_hash,1260frozen, match_args, kw_only, slots,1261weakref_slot)12621263# See if we're being called as @dataclass or @dataclass().1264if cls is None:1265# We're called with parens.1266return wrap12671268# We're called as @dataclass without parens.1269return wrap(cls)127012711272def fields(class_or_instance):1273"""Return a tuple describing the fields of this dataclass.12741275Accepts a dataclass or an instance of one. Tuple elements are of1276type Field.1277"""12781279# Might it be worth caching this, per class?1280try:1281fields = getattr(class_or_instance, _FIELDS)1282except AttributeError:1283raise TypeError('must be called with a dataclass type or instance') from None12841285# Exclude pseudo-fields. Note that fields is sorted by insertion1286# order, so the order of the tuple is as the fields were defined.1287return tuple(f for f in fields.values() if f._field_type is _FIELD)128812891290def _is_dataclass_instance(obj):1291"""Returns True if obj is an instance of a dataclass."""1292return hasattr(type(obj), _FIELDS)129312941295def is_dataclass(obj):1296"""Returns True if obj is a dataclass or an instance of a1297dataclass."""1298cls = obj if isinstance(obj, type) else type(obj)1299return hasattr(cls, _FIELDS)130013011302def asdict(obj, *, dict_factory=dict):1303"""Return the fields of a dataclass instance as a new dictionary mapping1304field names to field values.13051306Example usage::13071308@dataclass1309class C:1310x: int1311y: int13121313c = C(1, 2)1314assert asdict(c) == {'x': 1, 'y': 2}13151316If given, 'dict_factory' will be used instead of built-in dict.1317The function applies recursively to field values that are1318dataclass instances. This will also look into built-in containers:1319tuples, lists, and dicts. Other objects are copied with 'copy.deepcopy()'.1320"""1321if not _is_dataclass_instance(obj):1322raise TypeError("asdict() should be called on dataclass instances")1323return _asdict_inner(obj, dict_factory)132413251326def _asdict_inner(obj, dict_factory):1327if type(obj) in _ATOMIC_TYPES:1328return obj1329elif _is_dataclass_instance(obj):1330# fast path for the common case1331if dict_factory is dict:1332return {1333f.name: _asdict_inner(getattr(obj, f.name), dict)1334for f in fields(obj)1335}1336else:1337result = []1338for f in fields(obj):1339value = _asdict_inner(getattr(obj, f.name), dict_factory)1340result.append((f.name, value))1341return dict_factory(result)1342elif isinstance(obj, tuple) and hasattr(obj, '_fields'):1343# obj is a namedtuple. Recurse into it, but the returned1344# object is another namedtuple of the same type. This is1345# similar to how other list- or tuple-derived classes are1346# treated (see below), but we just need to create them1347# differently because a namedtuple's __init__ needs to be1348# called differently (see bpo-34363).13491350# I'm not using namedtuple's _asdict()1351# method, because:1352# - it does not recurse in to the namedtuple fields and1353# convert them to dicts (using dict_factory).1354# - I don't actually want to return a dict here. The main1355# use case here is json.dumps, and it handles converting1356# namedtuples to lists. Admittedly we're losing some1357# information here when we produce a json list instead of a1358# dict. Note that if we returned dicts here instead of1359# namedtuples, we could no longer call asdict() on a data1360# structure where a namedtuple was used as a dict key.13611362return type(obj)(*[_asdict_inner(v, dict_factory) for v in obj])1363elif isinstance(obj, (list, tuple)):1364# Assume we can create an object of this type by passing in a1365# generator (which is not true for namedtuples, handled1366# above).1367return type(obj)(_asdict_inner(v, dict_factory) for v in obj)1368elif isinstance(obj, dict):1369if hasattr(type(obj), 'default_factory'):1370# obj is a defaultdict, which has a different constructor from1371# dict as it requires the default_factory as its first arg.1372result = type(obj)(getattr(obj, 'default_factory'))1373for k, v in obj.items():1374result[_asdict_inner(k, dict_factory)] = _asdict_inner(v, dict_factory)1375return result1376return type(obj)((_asdict_inner(k, dict_factory),1377_asdict_inner(v, dict_factory))1378for k, v in obj.items())1379else:1380return copy.deepcopy(obj)138113821383def astuple(obj, *, tuple_factory=tuple):1384"""Return the fields of a dataclass instance as a new tuple of field values.13851386Example usage::13871388@dataclass1389class C:1390x: int1391y: int13921393c = C(1, 2)1394assert astuple(c) == (1, 2)13951396If given, 'tuple_factory' will be used instead of built-in tuple.1397The function applies recursively to field values that are1398dataclass instances. This will also look into built-in containers:1399tuples, lists, and dicts. Other objects are copied with 'copy.deepcopy()'.1400"""14011402if not _is_dataclass_instance(obj):1403raise TypeError("astuple() should be called on dataclass instances")1404return _astuple_inner(obj, tuple_factory)140514061407def _astuple_inner(obj, tuple_factory):1408if type(obj) in _ATOMIC_TYPES:1409return obj1410elif _is_dataclass_instance(obj):1411result = []1412for f in fields(obj):1413value = _astuple_inner(getattr(obj, f.name), tuple_factory)1414result.append(value)1415return tuple_factory(result)1416elif isinstance(obj, tuple) and hasattr(obj, '_fields'):1417# obj is a namedtuple. Recurse into it, but the returned1418# object is another namedtuple of the same type. This is1419# similar to how other list- or tuple-derived classes are1420# treated (see below), but we just need to create them1421# differently because a namedtuple's __init__ needs to be1422# called differently (see bpo-34363).1423return type(obj)(*[_astuple_inner(v, tuple_factory) for v in obj])1424elif isinstance(obj, (list, tuple)):1425# Assume we can create an object of this type by passing in a1426# generator (which is not true for namedtuples, handled1427# above).1428return type(obj)(_astuple_inner(v, tuple_factory) for v in obj)1429elif isinstance(obj, dict):1430obj_type = type(obj)1431if hasattr(obj_type, 'default_factory'):1432# obj is a defaultdict, which has a different constructor from1433# dict as it requires the default_factory as its first arg.1434result = obj_type(getattr(obj, 'default_factory'))1435for k, v in obj.items():1436result[_astuple_inner(k, tuple_factory)] = _astuple_inner(v, tuple_factory)1437return result1438return obj_type((_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory))1439for k, v in obj.items())1440else:1441return copy.deepcopy(obj)144214431444def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,1445repr=True, eq=True, order=False, unsafe_hash=False,1446frozen=False, match_args=True, kw_only=False, slots=False,1447weakref_slot=False, module=None):1448"""Return a new dynamically created dataclass.14491450The dataclass name will be 'cls_name'. 'fields' is an iterable1451of either (name), (name, type) or (name, type, Field) objects. If type is1452omitted, use the string 'typing.Any'. Field objects are created by1453the equivalent of calling 'field(name, type [, Field-info])'.::14541455C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,))14561457is equivalent to::14581459@dataclass1460class C(Base):1461x: 'typing.Any'1462y: int1463z: int = field(init=False)14641465For the bases and namespace parameters, see the builtin type() function.14661467The parameters init, repr, eq, order, unsafe_hash, frozen, match_args, kw_only,1468slots, and weakref_slot are passed to dataclass().14691470If module parameter is defined, the '__module__' attribute of the dataclass is1471set to that value.1472"""14731474if namespace is None:1475namespace = {}14761477# While we're looking through the field names, validate that they1478# are identifiers, are not keywords, and not duplicates.1479seen = set()1480annotations = {}1481defaults = {}1482for item in fields:1483if isinstance(item, str):1484name = item1485tp = 'typing.Any'1486elif len(item) == 2:1487name, tp, = item1488elif len(item) == 3:1489name, tp, spec = item1490defaults[name] = spec1491else:1492raise TypeError(f'Invalid field: {item!r}')14931494if not isinstance(name, str) or not name.isidentifier():1495raise TypeError(f'Field names must be valid identifiers: {name!r}')1496if keyword.iskeyword(name):1497raise TypeError(f'Field names must not be keywords: {name!r}')1498if name in seen:1499raise TypeError(f'Field name duplicated: {name!r}')15001501seen.add(name)1502annotations[name] = tp15031504# Update 'ns' with the user-supplied namespace plus our calculated values.1505def exec_body_callback(ns):1506ns.update(namespace)1507ns.update(defaults)1508ns['__annotations__'] = annotations15091510# We use `types.new_class()` instead of simply `type()` to allow dynamic creation1511# of generic dataclasses.1512cls = types.new_class(cls_name, bases, {}, exec_body_callback)15131514# For pickling to work, the __module__ variable needs to be set to the frame1515# where the dataclass is created.1516if module is None:1517try:1518module = sys._getframemodulename(1) or '__main__'1519except AttributeError:1520try:1521module = sys._getframe(1).f_globals.get('__name__', '__main__')1522except (AttributeError, ValueError):1523pass1524if module is not None:1525cls.__module__ = module15261527# Apply the normal decorator.1528return dataclass(cls, init=init, repr=repr, eq=eq, order=order,1529unsafe_hash=unsafe_hash, frozen=frozen,1530match_args=match_args, kw_only=kw_only, slots=slots,1531weakref_slot=weakref_slot)153215331534def replace(obj, /, **changes):1535"""Return a new object replacing specified fields with new values.15361537This is especially useful for frozen classes. Example usage::15381539@dataclass(frozen=True)1540class C:1541x: int1542y: int15431544c = C(1, 2)1545c1 = replace(c, x=3)1546assert c1.x == 3 and c1.y == 21547"""15481549# We're going to mutate 'changes', but that's okay because it's a1550# new dict, even if called with 'replace(obj, **my_changes)'.15511552if not _is_dataclass_instance(obj):1553raise TypeError("replace() should be called on dataclass instances")15541555# It's an error to have init=False fields in 'changes'.1556# If a field is not in 'changes', read its value from the provided obj.15571558for f in getattr(obj, _FIELDS).values():1559# Only consider normal fields or InitVars.1560if f._field_type is _FIELD_CLASSVAR:1561continue15621563if not f.init:1564# Error if this field is specified in changes.1565if f.name in changes:1566raise ValueError(f'field {f.name} is declared with '1567'init=False, it cannot be specified with '1568'replace()')1569continue15701571if f.name not in changes:1572if f._field_type is _FIELD_INITVAR and f.default is MISSING:1573raise ValueError(f"InitVar {f.name!r} "1574'must be specified with replace()')1575changes[f.name] = getattr(obj, f.name)15761577# Create the new object, which calls __init__() and1578# __post_init__() (if defined), using all of the init fields we've1579# added and/or left in 'changes'. If there are values supplied in1580# changes that aren't fields, this will correctly raise a1581# TypeError.1582return obj.__class__(**changes)158315841585