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