Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 1 | import sys |
| 2 | import types |
| 3 | from copy import deepcopy |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 4 | import inspect |
| 5 | |
| 6 | __all__ = ['dataclass', |
| 7 | 'field', |
Eric V. Smith | 8e4560a | 2018-03-21 17:10:22 -0400 | [diff] [blame^] | 8 | 'Field', |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 9 | 'FrozenInstanceError', |
| 10 | 'InitVar', |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 11 | 'MISSING', |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 12 | |
| 13 | # Helper functions. |
| 14 | 'fields', |
| 15 | 'asdict', |
| 16 | 'astuple', |
| 17 | 'make_dataclass', |
| 18 | 'replace', |
Eric V. Smith | e7ba013 | 2018-01-06 12:41:53 -0500 | [diff] [blame] | 19 | 'is_dataclass', |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 20 | ] |
| 21 | |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 22 | # Conditions for adding methods. The boxes indicate what action the |
| 23 | # dataclass decorator takes. For all of these tables, when I talk |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 24 | # about init=, repr=, eq=, order=, unsafe_hash=, or frozen=, I'm |
| 25 | # referring to the arguments to the @dataclass decorator. When |
| 26 | # checking if a dunder method already exists, I mean check for an |
| 27 | # entry in the class's __dict__. I never check to see if an |
| 28 | # attribute is defined in a base class. |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 29 | |
| 30 | # Key: |
| 31 | # +=========+=========================================+ |
| 32 | # + Value | Meaning | |
| 33 | # +=========+=========================================+ |
| 34 | # | <blank> | No action: no method is added. | |
| 35 | # +---------+-----------------------------------------+ |
| 36 | # | add | Generated method is added. | |
| 37 | # +---------+-----------------------------------------+ |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 38 | # | raise | TypeError is raised. | |
| 39 | # +---------+-----------------------------------------+ |
| 40 | # | None | Attribute is set to None. | |
| 41 | # +=========+=========================================+ |
| 42 | |
| 43 | # __init__ |
| 44 | # |
| 45 | # +--- init= parameter |
| 46 | # | |
| 47 | # v | | | |
| 48 | # | no | yes | <--- class has __init__ in __dict__? |
| 49 | # +=======+=======+=======+ |
| 50 | # | False | | | |
| 51 | # +-------+-------+-------+ |
| 52 | # | True | add | | <- the default |
| 53 | # +=======+=======+=======+ |
| 54 | |
| 55 | # __repr__ |
| 56 | # |
| 57 | # +--- repr= parameter |
| 58 | # | |
| 59 | # v | | | |
| 60 | # | no | yes | <--- class has __repr__ in __dict__? |
| 61 | # +=======+=======+=======+ |
| 62 | # | False | | | |
| 63 | # +-------+-------+-------+ |
| 64 | # | True | add | | <- the default |
| 65 | # +=======+=======+=======+ |
| 66 | |
| 67 | |
| 68 | # __setattr__ |
| 69 | # __delattr__ |
| 70 | # |
| 71 | # +--- frozen= parameter |
| 72 | # | |
| 73 | # v | | | |
| 74 | # | no | yes | <--- class has __setattr__ or __delattr__ in __dict__? |
| 75 | # +=======+=======+=======+ |
| 76 | # | False | | | <- the default |
| 77 | # +-------+-------+-------+ |
| 78 | # | True | add | raise | |
| 79 | # +=======+=======+=======+ |
| 80 | # Raise because not adding these methods would break the "frozen-ness" |
| 81 | # of the class. |
| 82 | |
| 83 | # __eq__ |
| 84 | # |
| 85 | # +--- eq= parameter |
| 86 | # | |
| 87 | # v | | | |
| 88 | # | no | yes | <--- class has __eq__ in __dict__? |
| 89 | # +=======+=======+=======+ |
| 90 | # | False | | | |
| 91 | # +-------+-------+-------+ |
| 92 | # | True | add | | <- the default |
| 93 | # +=======+=======+=======+ |
| 94 | |
| 95 | # __lt__ |
| 96 | # __le__ |
| 97 | # __gt__ |
| 98 | # __ge__ |
| 99 | # |
| 100 | # +--- order= parameter |
| 101 | # | |
| 102 | # v | | | |
| 103 | # | no | yes | <--- class has any comparison method in __dict__? |
| 104 | # +=======+=======+=======+ |
| 105 | # | False | | | <- the default |
| 106 | # +-------+-------+-------+ |
| 107 | # | True | add | raise | |
| 108 | # +=======+=======+=======+ |
| 109 | # Raise because to allow this case would interfere with using |
| 110 | # functools.total_ordering. |
| 111 | |
| 112 | # __hash__ |
| 113 | |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 114 | # +------------------- unsafe_hash= parameter |
| 115 | # | +----------- eq= parameter |
| 116 | # | | +--- frozen= parameter |
| 117 | # | | | |
| 118 | # v v v | | | |
| 119 | # | no | yes | <--- class has explicitly defined __hash__ |
| 120 | # +=======+=======+=======+========+========+ |
| 121 | # | False | False | False | | | No __eq__, use the base class __hash__ |
| 122 | # +-------+-------+-------+--------+--------+ |
| 123 | # | False | False | True | | | No __eq__, use the base class __hash__ |
| 124 | # +-------+-------+-------+--------+--------+ |
| 125 | # | False | True | False | None | | <-- the default, not hashable |
| 126 | # +-------+-------+-------+--------+--------+ |
| 127 | # | False | True | True | add | | Frozen, so hashable, allows override |
| 128 | # +-------+-------+-------+--------+--------+ |
| 129 | # | True | False | False | add | raise | Has no __eq__, but hashable |
| 130 | # +-------+-------+-------+--------+--------+ |
| 131 | # | True | False | True | add | raise | Has no __eq__, but hashable |
| 132 | # +-------+-------+-------+--------+--------+ |
| 133 | # | True | True | False | add | raise | Not frozen, but hashable |
| 134 | # +-------+-------+-------+--------+--------+ |
| 135 | # | True | True | True | add | raise | Frozen, so hashable |
| 136 | # +=======+=======+=======+========+========+ |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 137 | # For boxes that are blank, __hash__ is untouched and therefore |
| 138 | # inherited from the base class. If the base is object, then |
| 139 | # id-based hashing is used. |
| 140 | # Note that a class may have already __hash__=None if it specified an |
| 141 | # __eq__ method in the class body (not one that was created by |
| 142 | # @dataclass). |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 143 | # See _hash_action (below) for a coded version of this table. |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 144 | |
| 145 | |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 146 | # Raised when an attempt is made to modify a frozen class. |
| 147 | class FrozenInstanceError(AttributeError): pass |
| 148 | |
| 149 | # A sentinel object for default values to signal that a |
| 150 | # default-factory will be used. |
| 151 | # This is given a nice repr() which will appear in the function |
| 152 | # signature of dataclasses' constructors. |
| 153 | class _HAS_DEFAULT_FACTORY_CLASS: |
| 154 | def __repr__(self): |
| 155 | return '<factory>' |
| 156 | _HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS() |
| 157 | |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 158 | # A sentinel object to detect if a parameter is supplied or not. Use |
| 159 | # a class to give it a better repr. |
| 160 | class _MISSING_TYPE: |
| 161 | pass |
| 162 | MISSING = _MISSING_TYPE() |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 163 | |
| 164 | # Since most per-field metadata will be unused, create an empty |
| 165 | # read-only proxy that can be shared among all fields. |
| 166 | _EMPTY_METADATA = types.MappingProxyType({}) |
| 167 | |
| 168 | # Markers for the various kinds of fields and pseudo-fields. |
| 169 | _FIELD = object() # An actual field. |
| 170 | _FIELD_CLASSVAR = object() # Not a field, but a ClassVar. |
| 171 | _FIELD_INITVAR = object() # Not a field, but an InitVar. |
| 172 | |
| 173 | # The name of an attribute on the class where we store the Field |
| 174 | # objects. Also used to check if a class is a Data Class. |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 175 | _FIELDS = '__dataclass_fields__' |
| 176 | |
| 177 | # The name of an attribute on the class that stores the parameters to |
| 178 | # @dataclass. |
| 179 | _PARAMS = '__dataclass_params__' |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 180 | |
| 181 | # The name of the function, that if it exists, is called at the end of |
| 182 | # __init__. |
| 183 | _POST_INIT_NAME = '__post_init__' |
| 184 | |
| 185 | |
| 186 | class _InitVarMeta(type): |
| 187 | def __getitem__(self, params): |
| 188 | return self |
| 189 | |
| 190 | class InitVar(metaclass=_InitVarMeta): |
| 191 | pass |
| 192 | |
| 193 | |
| 194 | # Instances of Field are only ever created from within this module, |
| 195 | # and only from the field() function, although Field instances are |
| 196 | # exposed externally as (conceptually) read-only objects. |
| 197 | # name and type are filled in after the fact, not in __init__. They're |
| 198 | # not known at the time this class is instantiated, but it's |
| 199 | # convenient if they're available later. |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 200 | # When cls._FIELDS is filled in with a list of Field objects, the name |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 201 | # and type fields will have been populated. |
| 202 | class Field: |
| 203 | __slots__ = ('name', |
| 204 | 'type', |
| 205 | 'default', |
| 206 | 'default_factory', |
| 207 | 'repr', |
| 208 | 'hash', |
| 209 | 'init', |
| 210 | 'compare', |
| 211 | 'metadata', |
| 212 | '_field_type', # Private: not to be used by user code. |
| 213 | ) |
| 214 | |
| 215 | def __init__(self, default, default_factory, init, repr, hash, compare, |
| 216 | metadata): |
| 217 | self.name = None |
| 218 | self.type = None |
| 219 | self.default = default |
| 220 | self.default_factory = default_factory |
| 221 | self.init = init |
| 222 | self.repr = repr |
| 223 | self.hash = hash |
| 224 | self.compare = compare |
| 225 | self.metadata = (_EMPTY_METADATA |
| 226 | if metadata is None or len(metadata) == 0 else |
| 227 | types.MappingProxyType(metadata)) |
| 228 | self._field_type = None |
| 229 | |
| 230 | def __repr__(self): |
| 231 | return ('Field(' |
| 232 | f'name={self.name!r},' |
| 233 | f'type={self.type},' |
| 234 | f'default={self.default},' |
| 235 | f'default_factory={self.default_factory},' |
| 236 | f'init={self.init},' |
| 237 | f'repr={self.repr},' |
| 238 | f'hash={self.hash},' |
| 239 | f'compare={self.compare},' |
| 240 | f'metadata={self.metadata}' |
| 241 | ')') |
| 242 | |
| 243 | |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 244 | class _DataclassParams: |
| 245 | __slots__ = ('init', |
| 246 | 'repr', |
| 247 | 'eq', |
| 248 | 'order', |
| 249 | 'unsafe_hash', |
| 250 | 'frozen', |
| 251 | ) |
| 252 | def __init__(self, init, repr, eq, order, unsafe_hash, frozen): |
| 253 | self.init = init |
| 254 | self.repr = repr |
| 255 | self.eq = eq |
| 256 | self.order = order |
| 257 | self.unsafe_hash = unsafe_hash |
| 258 | self.frozen = frozen |
| 259 | |
| 260 | def __repr__(self): |
| 261 | return ('_DataclassParams(' |
| 262 | f'init={self.init},' |
| 263 | f'repr={self.repr},' |
| 264 | f'eq={self.eq},' |
| 265 | f'order={self.order},' |
| 266 | f'unsafe_hash={self.unsafe_hash},' |
| 267 | f'frozen={self.frozen}' |
| 268 | ')') |
| 269 | |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 270 | # This function is used instead of exposing Field creation directly, |
| 271 | # so that a type checker can be told (via overloads) that this is a |
| 272 | # function whose type depends on its parameters. |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 273 | def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 274 | hash=None, compare=True, metadata=None): |
| 275 | """Return an object to identify dataclass fields. |
| 276 | |
| 277 | default is the default value of the field. default_factory is a |
| 278 | 0-argument function called to initialize a field's value. If init |
| 279 | is True, the field will be a parameter to the class's __init__() |
| 280 | function. If repr is True, the field will be included in the |
| 281 | object's repr(). If hash is True, the field will be included in |
| 282 | the object's hash(). If compare is True, the field will be used in |
| 283 | comparison functions. metadata, if specified, must be a mapping |
| 284 | which is stored but not otherwise examined by dataclass. |
| 285 | |
| 286 | It is an error to specify both default and default_factory. |
| 287 | """ |
| 288 | |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 289 | if default is not MISSING and default_factory is not MISSING: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 290 | raise ValueError('cannot specify both default and default_factory') |
| 291 | return Field(default, default_factory, init, repr, hash, compare, |
| 292 | metadata) |
| 293 | |
| 294 | |
| 295 | def _tuple_str(obj_name, fields): |
| 296 | # Return a string representing each field of obj_name as a tuple |
| 297 | # member. So, if fields is ['x', 'y'] and obj_name is "self", |
| 298 | # return "(self.x,self.y)". |
| 299 | |
| 300 | # Special case for the 0-tuple. |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 301 | if not fields: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 302 | return '()' |
| 303 | # Note the trailing comma, needed if this turns out to be a 1-tuple. |
| 304 | return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)' |
| 305 | |
| 306 | |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 307 | def _create_fn(name, args, body, *, globals=None, locals=None, |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 308 | return_type=MISSING): |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 309 | # Note that we mutate locals when exec() is called. Caller beware! |
| 310 | if locals is None: |
| 311 | locals = {} |
| 312 | return_annotation = '' |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 313 | if return_type is not MISSING: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 314 | locals['_return_type'] = return_type |
| 315 | return_annotation = '->_return_type' |
| 316 | args = ','.join(args) |
| 317 | body = '\n'.join(f' {b}' for b in body) |
| 318 | |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 319 | # Compute the text of the entire function. |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 320 | txt = f'def {name}({args}){return_annotation}:\n{body}' |
| 321 | |
| 322 | exec(txt, globals, locals) |
| 323 | return locals[name] |
| 324 | |
| 325 | |
| 326 | def _field_assign(frozen, name, value, self_name): |
| 327 | # If we're a frozen class, then assign to our fields in __init__ |
| 328 | # via object.__setattr__. Otherwise, just use a simple |
| 329 | # assignment. |
| 330 | # self_name is what "self" is called in this function: don't |
| 331 | # hard-code "self", since that might be a field name. |
| 332 | if frozen: |
| 333 | return f'object.__setattr__({self_name},{name!r},{value})' |
| 334 | return f'{self_name}.{name}={value}' |
| 335 | |
| 336 | |
| 337 | def _field_init(f, frozen, globals, self_name): |
| 338 | # Return the text of the line in the body of __init__ that will |
| 339 | # initialize this field. |
| 340 | |
| 341 | default_name = f'_dflt_{f.name}' |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 342 | if f.default_factory is not MISSING: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 343 | if f.init: |
| 344 | # This field has a default factory. If a parameter is |
| 345 | # given, use it. If not, call the factory. |
| 346 | globals[default_name] = f.default_factory |
| 347 | value = (f'{default_name}() ' |
| 348 | f'if {f.name} is _HAS_DEFAULT_FACTORY ' |
| 349 | f'else {f.name}') |
| 350 | else: |
| 351 | # This is a field that's not in the __init__ params, but |
| 352 | # has a default factory function. It needs to be |
| 353 | # initialized here by calling the factory function, |
| 354 | # because there's no other way to initialize it. |
| 355 | |
| 356 | # For a field initialized with a default=defaultvalue, the |
| 357 | # class dict just has the default value |
| 358 | # (cls.fieldname=defaultvalue). But that won't work for a |
| 359 | # default factory, the factory must be called in __init__ |
| 360 | # and we must assign that to self.fieldname. We can't |
| 361 | # fall back to the class dict's value, both because it's |
| 362 | # not set, and because it might be different per-class |
| 363 | # (which, after all, is why we have a factory function!). |
| 364 | |
| 365 | globals[default_name] = f.default_factory |
| 366 | value = f'{default_name}()' |
| 367 | else: |
| 368 | # No default factory. |
| 369 | if f.init: |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 370 | if f.default is MISSING: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 371 | # There's no default, just do an assignment. |
| 372 | value = f.name |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 373 | elif f.default is not MISSING: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 374 | globals[default_name] = f.default |
| 375 | value = f.name |
| 376 | else: |
| 377 | # This field does not need initialization. Signify that to |
| 378 | # the caller by returning None. |
| 379 | return None |
| 380 | |
| 381 | # Only test this now, so that we can create variables for the |
| 382 | # default. However, return None to signify that we're not going |
| 383 | # to actually do the assignment statement for InitVars. |
| 384 | if f._field_type == _FIELD_INITVAR: |
| 385 | return None |
| 386 | |
| 387 | # Now, actually generate the field assignment. |
| 388 | return _field_assign(frozen, f.name, value, self_name) |
| 389 | |
| 390 | |
| 391 | def _init_param(f): |
| 392 | # Return the __init__ parameter string for this field. |
| 393 | # For example, the equivalent of 'x:int=3' (except instead of 'int', |
| 394 | # reference a variable set to int, and instead of '3', reference a |
| 395 | # variable set to 3). |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 396 | if f.default is MISSING and f.default_factory is MISSING: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 397 | # There's no default, and no default_factory, just |
| 398 | # output the variable name and type. |
| 399 | default = '' |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 400 | elif f.default is not MISSING: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 401 | # There's a default, this will be the name that's used to look it up. |
| 402 | default = f'=_dflt_{f.name}' |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 403 | elif f.default_factory is not MISSING: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 404 | # There's a factory function. Set a marker. |
| 405 | default = '=_HAS_DEFAULT_FACTORY' |
| 406 | return f'{f.name}:_type_{f.name}{default}' |
| 407 | |
| 408 | |
| 409 | def _init_fn(fields, frozen, has_post_init, self_name): |
| 410 | # fields contains both real fields and InitVar pseudo-fields. |
| 411 | |
| 412 | # Make sure we don't have fields without defaults following fields |
| 413 | # with defaults. This actually would be caught when exec-ing the |
| 414 | # function source code, but catching it here gives a better error |
| 415 | # message, and future-proofs us in case we build up the function |
| 416 | # using ast. |
| 417 | seen_default = False |
| 418 | for f in fields: |
| 419 | # Only consider fields in the __init__ call. |
| 420 | if f.init: |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 421 | 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] | 422 | seen_default = True |
| 423 | elif seen_default: |
| 424 | raise TypeError(f'non-default argument {f.name!r} ' |
| 425 | 'follows default argument') |
| 426 | |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 427 | globals = {'MISSING': MISSING, |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 428 | '_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY} |
| 429 | |
| 430 | body_lines = [] |
| 431 | for f in fields: |
| 432 | # Do not initialize the pseudo-fields, only the real ones. |
| 433 | line = _field_init(f, frozen, globals, self_name) |
| 434 | if line is not None: |
| 435 | # line is None means that this field doesn't require |
| 436 | # initialization. Just skip it. |
| 437 | body_lines.append(line) |
| 438 | |
| 439 | # Does this class have a post-init function? |
| 440 | if has_post_init: |
| 441 | params_str = ','.join(f.name for f in fields |
| 442 | if f._field_type is _FIELD_INITVAR) |
| 443 | body_lines += [f'{self_name}.{_POST_INIT_NAME}({params_str})'] |
| 444 | |
| 445 | # If no body lines, use 'pass'. |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 446 | if not body_lines: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 447 | body_lines = ['pass'] |
| 448 | |
| 449 | locals = {f'_type_{f.name}': f.type for f in fields} |
| 450 | return _create_fn('__init__', |
| 451 | [self_name] +[_init_param(f) for f in fields if f.init], |
| 452 | body_lines, |
| 453 | locals=locals, |
| 454 | globals=globals, |
| 455 | return_type=None) |
| 456 | |
| 457 | |
| 458 | def _repr_fn(fields): |
| 459 | return _create_fn('__repr__', |
| 460 | ['self'], |
| 461 | ['return self.__class__.__qualname__ + f"(' + |
| 462 | ', '.join([f"{f.name}={{self.{f.name}!r}}" |
| 463 | for f in fields]) + |
| 464 | ')"']) |
| 465 | |
| 466 | |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 467 | def _frozen_get_del_attr(cls, fields): |
| 468 | # XXX: globals is modified on the first call to _create_fn, then the |
| 469 | # modified version is used in the second call. Is this okay? |
| 470 | globals = {'cls': cls, |
| 471 | 'FrozenInstanceError': FrozenInstanceError} |
| 472 | if fields: |
| 473 | fields_str = '(' + ','.join(repr(f.name) for f in fields) + ',)' |
| 474 | else: |
| 475 | # Special case for the zero-length tuple. |
| 476 | fields_str = '()' |
| 477 | return (_create_fn('__setattr__', |
| 478 | ('self', 'name', 'value'), |
| 479 | (f'if type(self) is cls or name in {fields_str}:', |
| 480 | ' raise FrozenInstanceError(f"cannot assign to field {name!r}")', |
| 481 | f'super(cls, self).__setattr__(name, value)'), |
| 482 | globals=globals), |
| 483 | _create_fn('__delattr__', |
| 484 | ('self', 'name'), |
| 485 | (f'if type(self) is cls or name in {fields_str}:', |
| 486 | ' raise FrozenInstanceError(f"cannot delete field {name!r}")', |
| 487 | f'super(cls, self).__delattr__(name)'), |
| 488 | globals=globals), |
| 489 | ) |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 490 | |
| 491 | |
| 492 | def _cmp_fn(name, op, self_tuple, other_tuple): |
| 493 | # Create a comparison function. If the fields in the object are |
| 494 | # named 'x' and 'y', then self_tuple is the string |
| 495 | # '(self.x,self.y)' and other_tuple is the string |
| 496 | # '(other.x,other.y)'. |
| 497 | |
| 498 | return _create_fn(name, |
| 499 | ['self', 'other'], |
| 500 | [ 'if other.__class__ is self.__class__:', |
| 501 | f' return {self_tuple}{op}{other_tuple}', |
| 502 | 'return NotImplemented']) |
| 503 | |
| 504 | |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 505 | def _hash_fn(fields): |
| 506 | self_tuple = _tuple_str('self', fields) |
| 507 | return _create_fn('__hash__', |
| 508 | ['self'], |
| 509 | [f'return hash({self_tuple})']) |
| 510 | |
| 511 | |
| 512 | def _get_field(cls, a_name, a_type): |
| 513 | # Return a Field object, for this field name and type. ClassVars |
| 514 | # and InitVars are also returned, but marked as such (see |
| 515 | # f._field_type). |
| 516 | |
Eric V. Smith | 8e4560a | 2018-03-21 17:10:22 -0400 | [diff] [blame^] | 517 | # If the default value isn't derived from Field, then it's |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 518 | # only a normal default value. Convert it to a Field(). |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 519 | default = getattr(cls, a_name, MISSING) |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 520 | if isinstance(default, Field): |
| 521 | f = default |
| 522 | else: |
Eric V. Smith | 7389fd9 | 2018-03-19 21:07:51 -0400 | [diff] [blame] | 523 | if isinstance(default, types.MemberDescriptorType): |
| 524 | # This is a field in __slots__, so it has no default value. |
| 525 | default = MISSING |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 526 | f = field(default=default) |
| 527 | |
| 528 | # Assume it's a normal field until proven otherwise. |
| 529 | f._field_type = _FIELD |
| 530 | |
| 531 | # Only at this point do we know the name and the type. Set them. |
| 532 | f.name = a_name |
| 533 | f.type = a_type |
| 534 | |
| 535 | # If typing has not been imported, then it's impossible for |
| 536 | # any annotation to be a ClassVar. So, only look for ClassVar |
| 537 | # if typing has been imported. |
| 538 | typing = sys.modules.get('typing') |
| 539 | if typing is not None: |
| 540 | # This test uses a typing internal class, but it's the best |
| 541 | # way to test if this is a ClassVar. |
Ivan Levkivskyi | d911e40 | 2018-01-20 11:23:59 +0000 | [diff] [blame] | 542 | if (type(a_type) is typing._GenericAlias and |
| 543 | a_type.__origin__ is typing.ClassVar): |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 544 | # This field is a ClassVar, so it's not a field. |
| 545 | f._field_type = _FIELD_CLASSVAR |
| 546 | |
| 547 | if f._field_type is _FIELD: |
| 548 | # Check if this is an InitVar. |
| 549 | if a_type is InitVar: |
| 550 | # InitVars are not fields, either. |
| 551 | f._field_type = _FIELD_INITVAR |
| 552 | |
| 553 | # Validations for fields. This is delayed until now, instead of |
| 554 | # in the Field() constructor, since only here do we know the field |
| 555 | # name, which allows better error reporting. |
| 556 | |
| 557 | # Special restrictions for ClassVar and InitVar. |
| 558 | if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR): |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 559 | if f.default_factory is not MISSING: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 560 | raise TypeError(f'field {f.name} cannot have a ' |
| 561 | 'default factory') |
| 562 | # Should I check for other field settings? default_factory |
| 563 | # seems the most serious to check for. Maybe add others. For |
| 564 | # example, how about init=False (or really, |
| 565 | # init=<not-the-default-init-value>)? It makes no sense for |
| 566 | # ClassVar and InitVar to specify init=<anything>. |
| 567 | |
| 568 | # For real fields, disallow mutable defaults for known types. |
| 569 | if f._field_type is _FIELD and isinstance(f.default, (list, dict, set)): |
| 570 | raise ValueError(f'mutable default {type(f.default)} for field ' |
| 571 | f'{f.name} is not allowed: use default_factory') |
| 572 | |
| 573 | return f |
| 574 | |
| 575 | |
| 576 | def _find_fields(cls): |
| 577 | # Return a list of Field objects, in order, for this class (and no |
Eric V. Smith | 8f6eccd | 2018-03-20 22:00:23 -0400 | [diff] [blame] | 578 | # base classes). Fields are found from the class dict's |
| 579 | # __annotations__ (which is guaranteed to be ordered). Default |
| 580 | # values are from class attributes, if a field has a default. If |
| 581 | # the default value is a Field(), then it contains additional |
| 582 | # info beyond (and possibly including) the actual default value. |
| 583 | # Pseudo-fields ClassVars and InitVars are included, despite the |
| 584 | # fact that they're not real fields. That's dealt with later. |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 585 | |
Eric V. Smith | 8f6eccd | 2018-03-20 22:00:23 -0400 | [diff] [blame] | 586 | # If __annotations__ isn't present, then this class adds no new |
| 587 | # annotations. |
| 588 | annotations = cls.__dict__.get('__annotations__', {}) |
| 589 | return [_get_field(cls, name, type) for name, type in annotations.items()] |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 590 | |
| 591 | |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 592 | def _set_new_attribute(cls, name, value): |
| 593 | # Never overwrites an existing attribute. Returns True if the |
| 594 | # attribute already exists. |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 595 | if name in cls.__dict__: |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 596 | return True |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 597 | setattr(cls, name, value) |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 598 | return False |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 599 | |
| 600 | |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 601 | # Decide if/how we're going to create a hash function. Key is |
| 602 | # (unsafe_hash, eq, frozen, does-hash-exist). Value is the action to |
| 603 | # take. |
| 604 | # Actions: |
| 605 | # '': Do nothing. |
| 606 | # 'none': Set __hash__ to None. |
| 607 | # 'add': Always add a generated __hash__function. |
| 608 | # 'exception': Raise an exception. |
| 609 | # |
| 610 | # +-------------------------------------- unsafe_hash? |
| 611 | # | +------------------------------- eq? |
| 612 | # | | +------------------------ frozen? |
| 613 | # | | | +---------------- has-explicit-hash? |
| 614 | # | | | | |
| 615 | # | | | | +------- action |
| 616 | # | | | | | |
| 617 | # v v v v v |
| 618 | _hash_action = {(False, False, False, False): (''), |
| 619 | (False, False, False, True ): (''), |
| 620 | (False, False, True, False): (''), |
| 621 | (False, False, True, True ): (''), |
| 622 | (False, True, False, False): ('none'), |
| 623 | (False, True, False, True ): (''), |
| 624 | (False, True, True, False): ('add'), |
| 625 | (False, True, True, True ): (''), |
| 626 | (True, False, False, False): ('add'), |
| 627 | (True, False, False, True ): ('exception'), |
| 628 | (True, False, True, False): ('add'), |
| 629 | (True, False, True, True ): ('exception'), |
| 630 | (True, True, False, False): ('add'), |
| 631 | (True, True, False, True ): ('exception'), |
| 632 | (True, True, True, False): ('add'), |
| 633 | (True, True, True, True ): ('exception'), |
| 634 | } |
| 635 | # See https://bugs.python.org/issue32929#msg312829 for an if-statement |
| 636 | # version of this table. |
| 637 | |
| 638 | |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 639 | def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen): |
Eric V. Smith | d138892 | 2018-01-07 14:30:17 -0500 | [diff] [blame] | 640 | # Now that dicts retain insertion order, there's no reason to use |
| 641 | # an ordered dict. I am leveraging that ordering here, because |
| 642 | # derived class fields overwrite base class fields, but the order |
| 643 | # is defined by the base class, which is found first. |
| 644 | fields = {} |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 645 | |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 646 | setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order, |
| 647 | unsafe_hash, frozen)) |
| 648 | |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 649 | # Find our base classes in reverse MRO order, and exclude |
| 650 | # ourselves. In reversed order so that more derived classes |
| 651 | # override earlier field definitions in base classes. |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 652 | # As long as we're iterating over them, see if any are frozen. |
| 653 | any_frozen_base = False |
| 654 | has_dataclass_bases = False |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 655 | for b in cls.__mro__[-1:0:-1]: |
| 656 | # Only process classes that have been processed by our |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 657 | # decorator. That is, they have a _FIELDS attribute. |
| 658 | base_fields = getattr(b, _FIELDS, None) |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 659 | if base_fields: |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 660 | has_dataclass_bases = True |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 661 | for f in base_fields.values(): |
| 662 | fields[f.name] = f |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 663 | if getattr(b, _PARAMS).frozen: |
| 664 | any_frozen_base = True |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 665 | |
| 666 | # Now find fields in our class. While doing so, validate some |
| 667 | # things, and set the default values (as class attributes) |
| 668 | # where we can. |
| 669 | for f in _find_fields(cls): |
| 670 | fields[f.name] = f |
| 671 | |
| 672 | # If the class attribute (which is the default value for |
| 673 | # this field) exists and is of type 'Field', replace it |
| 674 | # with the real default. This is so that normal class |
| 675 | # introspection sees a real default value, not a Field. |
| 676 | if isinstance(getattr(cls, f.name, None), Field): |
Eric V. Smith | 03220fd | 2017-12-29 13:59:58 -0500 | [diff] [blame] | 677 | if f.default is MISSING: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 678 | # If there's no default, delete the class attribute. |
| 679 | # This happens if we specify field(repr=False), for |
| 680 | # example (that is, we specified a field object, but |
| 681 | # no default value). Also if we're using a default |
| 682 | # factory. The class attribute should not be set at |
| 683 | # all in the post-processed class. |
| 684 | delattr(cls, f.name) |
| 685 | else: |
| 686 | setattr(cls, f.name, f.default) |
| 687 | |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 688 | # Check rules that apply if we are derived from any dataclasses. |
| 689 | if has_dataclass_bases: |
| 690 | # Raise an exception if any of our bases are frozen, but we're not. |
| 691 | if any_frozen_base and not frozen: |
| 692 | raise TypeError('cannot inherit non-frozen dataclass from a ' |
| 693 | 'frozen one') |
Eric V. Smith | 2fa6b9e | 2018-02-26 20:38:33 -0500 | [diff] [blame] | 694 | |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 695 | # Raise an exception if we're frozen, but none of our bases are. |
| 696 | if not any_frozen_base and frozen: |
| 697 | raise TypeError('cannot inherit frozen dataclass from a ' |
| 698 | 'non-frozen one') |
Eric V. Smith | 2fa6b9e | 2018-02-26 20:38:33 -0500 | [diff] [blame] | 699 | |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 700 | # Remember all of the fields on our class (including bases). This also |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 701 | # marks this class as being a dataclass. |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 702 | setattr(cls, _FIELDS, fields) |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 703 | |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 704 | # Was this class defined with an explicit __hash__? Note that if |
| 705 | # __eq__ is defined in this class, then python will automatically |
| 706 | # set __hash__ to None. This is a heuristic, as it's possible |
| 707 | # that such a __hash__ == None was not auto-generated, but it |
| 708 | # close enough. |
| 709 | class_hash = cls.__dict__.get('__hash__', MISSING) |
| 710 | has_explicit_hash = not (class_hash is MISSING or |
| 711 | (class_hash is None and '__eq__' in cls.__dict__)) |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 712 | |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 713 | # If we're generating ordering methods, we must be generating |
| 714 | # the eq methods. |
| 715 | if order and not eq: |
| 716 | raise ValueError('eq must be true if order is true') |
| 717 | |
| 718 | if init: |
| 719 | # Does this class have a post-init function? |
| 720 | has_post_init = hasattr(cls, _POST_INIT_NAME) |
| 721 | |
| 722 | # Include InitVars and regular fields (so, not ClassVars). |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 723 | flds = [f for f in fields.values() |
| 724 | if f._field_type in (_FIELD, _FIELD_INITVAR)] |
| 725 | _set_new_attribute(cls, '__init__', |
| 726 | _init_fn(flds, |
Eric V. Smith | 2fa6b9e | 2018-02-26 20:38:33 -0500 | [diff] [blame] | 727 | frozen, |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 728 | has_post_init, |
| 729 | # The name to use for the "self" param |
| 730 | # in __init__. Use "self" if possible. |
| 731 | '__dataclass_self__' if 'self' in fields |
| 732 | else 'self', |
| 733 | )) |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 734 | |
| 735 | # Get the fields as a list, and include only real fields. This is |
| 736 | # used in all of the following methods. |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 737 | 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] | 738 | |
| 739 | if repr: |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 740 | flds = [f for f in field_list if f.repr] |
| 741 | _set_new_attribute(cls, '__repr__', _repr_fn(flds)) |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 742 | |
| 743 | if eq: |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 744 | # Create _eq__ method. There's no need for a __ne__ method, |
| 745 | # since python will call __eq__ and negate it. |
| 746 | flds = [f for f in field_list if f.compare] |
| 747 | self_tuple = _tuple_str('self', flds) |
| 748 | other_tuple = _tuple_str('other', flds) |
| 749 | _set_new_attribute(cls, '__eq__', |
| 750 | _cmp_fn('__eq__', '==', |
| 751 | self_tuple, other_tuple)) |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 752 | |
| 753 | if order: |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 754 | # Create and set the ordering methods. |
| 755 | flds = [f for f in field_list if f.compare] |
| 756 | self_tuple = _tuple_str('self', flds) |
| 757 | other_tuple = _tuple_str('other', flds) |
| 758 | for name, op in [('__lt__', '<'), |
| 759 | ('__le__', '<='), |
| 760 | ('__gt__', '>'), |
| 761 | ('__ge__', '>='), |
| 762 | ]: |
| 763 | if _set_new_attribute(cls, name, |
| 764 | _cmp_fn(name, op, self_tuple, other_tuple)): |
| 765 | raise TypeError(f'Cannot overwrite attribute {name} ' |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 766 | f'in class {cls.__name__}. Consider using ' |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 767 | 'functools.total_ordering') |
| 768 | |
Eric V. Smith | 2fa6b9e | 2018-02-26 20:38:33 -0500 | [diff] [blame] | 769 | if frozen: |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 770 | # XXX: Which fields are frozen? InitVar? ClassVar? hashed-only? |
| 771 | for fn in _frozen_get_del_attr(cls, field_list): |
| 772 | if _set_new_attribute(cls, fn.__name__, fn): |
| 773 | raise TypeError(f'Cannot overwrite attribute {fn.__name__} ' |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 774 | f'in class {cls.__name__}') |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 775 | |
| 776 | # Decide if/how we're going to create a hash function. |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 777 | hash_action = _hash_action[bool(unsafe_hash), |
| 778 | bool(eq), |
| 779 | bool(frozen), |
| 780 | has_explicit_hash] |
| 781 | |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 782 | # No need to call _set_new_attribute here, since we already know if |
| 783 | # we're overwriting a __hash__ or not. |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 784 | if hash_action == '': |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 785 | # Do nothing. |
| 786 | pass |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 787 | elif hash_action == 'none': |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 788 | cls.__hash__ = None |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 789 | elif hash_action == 'add': |
| 790 | flds = [f for f in field_list if (f.compare if f.hash is None else f.hash)] |
| 791 | cls.__hash__ = _hash_fn(flds) |
| 792 | elif hash_action == 'exception': |
| 793 | # Raise an exception. |
| 794 | raise TypeError(f'Cannot overwrite attribute __hash__ ' |
| 795 | f'in class {cls.__name__}') |
Eric V. Smith | ea8fc52 | 2018-01-27 19:07:40 -0500 | [diff] [blame] | 796 | else: |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 797 | assert False, f"can't get here: {hash_action}" |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 798 | |
| 799 | if not getattr(cls, '__doc__'): |
| 800 | # Create a class doc-string. |
| 801 | cls.__doc__ = (cls.__name__ + |
| 802 | str(inspect.signature(cls)).replace(' -> None', '')) |
| 803 | |
| 804 | return cls |
| 805 | |
| 806 | |
| 807 | # _cls should never be specified by keyword, so start it with an |
Raymond Hettinger | d55209d | 2018-01-10 20:56:41 -0800 | [diff] [blame] | 808 | # underscore. The presence of _cls is used to detect if this |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 809 | # decorator is being called with parameters or not. |
| 810 | 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] | 811 | unsafe_hash=False, frozen=False): |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 812 | """Returns the same class as was passed in, with dunder methods |
| 813 | added based on the fields defined in the class. |
| 814 | |
| 815 | Examines PEP 526 __annotations__ to determine fields. |
| 816 | |
| 817 | If init is true, an __init__() method is added to the class. If |
| 818 | 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] | 819 | comparison dunder methods are added. If unsafe_hash is true, a |
| 820 | __hash__() method function is added. If frozen is true, fields may |
| 821 | not be assigned to after instance creation. |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 822 | """ |
| 823 | |
| 824 | def wrap(cls): |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 825 | return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen) |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 826 | |
| 827 | # See if we're being called as @dataclass or @dataclass(). |
| 828 | if _cls is None: |
| 829 | # We're called with parens. |
| 830 | return wrap |
| 831 | |
| 832 | # We're called as @dataclass without parens. |
| 833 | return wrap(_cls) |
| 834 | |
| 835 | |
| 836 | def fields(class_or_instance): |
| 837 | """Return a tuple describing the fields of this dataclass. |
| 838 | |
| 839 | Accepts a dataclass or an instance of one. Tuple elements are of |
| 840 | type Field. |
| 841 | """ |
| 842 | |
| 843 | # Might it be worth caching this, per class? |
| 844 | try: |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 845 | fields = getattr(class_or_instance, _FIELDS) |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 846 | except AttributeError: |
| 847 | raise TypeError('must be called with a dataclass type or instance') |
| 848 | |
Eric V. Smith | d138892 | 2018-01-07 14:30:17 -0500 | [diff] [blame] | 849 | # Exclude pseudo-fields. Note that fields is sorted by insertion |
| 850 | # 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] | 851 | return tuple(f for f in fields.values() if f._field_type is _FIELD) |
| 852 | |
| 853 | |
Eric V. Smith | e7ba013 | 2018-01-06 12:41:53 -0500 | [diff] [blame] | 854 | def _is_dataclass_instance(obj): |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 855 | """Returns True if obj is an instance of a dataclass.""" |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 856 | return not isinstance(obj, type) and hasattr(obj, _FIELDS) |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 857 | |
| 858 | |
Eric V. Smith | e7ba013 | 2018-01-06 12:41:53 -0500 | [diff] [blame] | 859 | def is_dataclass(obj): |
| 860 | """Returns True if obj is a dataclass or an instance of a |
| 861 | dataclass.""" |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 862 | return hasattr(obj, _FIELDS) |
Eric V. Smith | e7ba013 | 2018-01-06 12:41:53 -0500 | [diff] [blame] | 863 | |
| 864 | |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 865 | def asdict(obj, *, dict_factory=dict): |
| 866 | """Return the fields of a dataclass instance as a new dictionary mapping |
| 867 | field names to field values. |
| 868 | |
| 869 | Example usage: |
| 870 | |
| 871 | @dataclass |
| 872 | class C: |
| 873 | x: int |
| 874 | y: int |
| 875 | |
| 876 | c = C(1, 2) |
| 877 | assert asdict(c) == {'x': 1, 'y': 2} |
| 878 | |
| 879 | If given, 'dict_factory' will be used instead of built-in dict. |
| 880 | The function applies recursively to field values that are |
| 881 | dataclass instances. This will also look into built-in containers: |
| 882 | tuples, lists, and dicts. |
| 883 | """ |
Eric V. Smith | e7ba013 | 2018-01-06 12:41:53 -0500 | [diff] [blame] | 884 | if not _is_dataclass_instance(obj): |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 885 | raise TypeError("asdict() should be called on dataclass instances") |
| 886 | return _asdict_inner(obj, dict_factory) |
| 887 | |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 888 | |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 889 | def _asdict_inner(obj, dict_factory): |
Eric V. Smith | e7ba013 | 2018-01-06 12:41:53 -0500 | [diff] [blame] | 890 | if _is_dataclass_instance(obj): |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 891 | result = [] |
| 892 | for f in fields(obj): |
| 893 | value = _asdict_inner(getattr(obj, f.name), dict_factory) |
| 894 | result.append((f.name, value)) |
| 895 | return dict_factory(result) |
| 896 | elif isinstance(obj, (list, tuple)): |
| 897 | return type(obj)(_asdict_inner(v, dict_factory) for v in obj) |
| 898 | elif isinstance(obj, dict): |
| 899 | return type(obj)((_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) |
| 900 | for k, v in obj.items()) |
| 901 | else: |
| 902 | return deepcopy(obj) |
| 903 | |
| 904 | |
| 905 | def astuple(obj, *, tuple_factory=tuple): |
| 906 | """Return the fields of a dataclass instance as a new tuple of field values. |
| 907 | |
| 908 | Example usage:: |
| 909 | |
| 910 | @dataclass |
| 911 | class C: |
| 912 | x: int |
| 913 | y: int |
| 914 | |
| 915 | c = C(1, 2) |
Raymond Hettinger | d55209d | 2018-01-10 20:56:41 -0800 | [diff] [blame] | 916 | assert astuple(c) == (1, 2) |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 917 | |
| 918 | If given, 'tuple_factory' will be used instead of built-in tuple. |
| 919 | The function applies recursively to field values that are |
| 920 | dataclass instances. This will also look into built-in containers: |
| 921 | tuples, lists, and dicts. |
| 922 | """ |
| 923 | |
Eric V. Smith | e7ba013 | 2018-01-06 12:41:53 -0500 | [diff] [blame] | 924 | if not _is_dataclass_instance(obj): |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 925 | raise TypeError("astuple() should be called on dataclass instances") |
| 926 | return _astuple_inner(obj, tuple_factory) |
| 927 | |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 928 | |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 929 | def _astuple_inner(obj, tuple_factory): |
Eric V. Smith | e7ba013 | 2018-01-06 12:41:53 -0500 | [diff] [blame] | 930 | if _is_dataclass_instance(obj): |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 931 | result = [] |
| 932 | for f in fields(obj): |
| 933 | value = _astuple_inner(getattr(obj, f.name), tuple_factory) |
| 934 | result.append(value) |
| 935 | return tuple_factory(result) |
| 936 | elif isinstance(obj, (list, tuple)): |
| 937 | return type(obj)(_astuple_inner(v, tuple_factory) for v in obj) |
| 938 | elif isinstance(obj, dict): |
| 939 | return type(obj)((_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory)) |
| 940 | for k, v in obj.items()) |
| 941 | else: |
| 942 | return deepcopy(obj) |
| 943 | |
| 944 | |
Eric V. Smith | d80b443 | 2018-01-06 17:09:58 -0500 | [diff] [blame] | 945 | def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, |
Eric V. Smith | 5da8cfb | 2018-03-01 08:01:41 -0500 | [diff] [blame] | 946 | repr=True, eq=True, order=False, unsafe_hash=False, |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 947 | frozen=False): |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 948 | """Return a new dynamically created dataclass. |
| 949 | |
Eric V. Smith | ed7d429 | 2018-01-06 16:14:03 -0500 | [diff] [blame] | 950 | The dataclass name will be 'cls_name'. 'fields' is an iterable |
| 951 | of either (name), (name, type) or (name, type, Field) objects. If type is |
| 952 | omitted, use the string 'typing.Any'. Field objects are created by |
Eric V. Smith | d327ae6 | 2018-01-07 08:19:45 -0500 | [diff] [blame] | 953 | the equivalent of calling 'field(name, type [, Field-info])'. |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 954 | |
Raymond Hettinger | d55209d | 2018-01-10 20:56:41 -0800 | [diff] [blame] | 955 | 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] | 956 | |
| 957 | is equivalent to: |
| 958 | |
| 959 | @dataclass |
| 960 | class C(Base): |
Raymond Hettinger | d55209d | 2018-01-10 20:56:41 -0800 | [diff] [blame] | 961 | x: 'typing.Any' |
| 962 | y: int |
| 963 | z: int = field(init=False) |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 964 | |
Raymond Hettinger | d55209d | 2018-01-10 20:56:41 -0800 | [diff] [blame] | 965 | For the bases and namespace parameters, see the builtin type() function. |
Eric V. Smith | d80b443 | 2018-01-06 17:09:58 -0500 | [diff] [blame] | 966 | |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 967 | 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] | 968 | dataclass(). |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 969 | """ |
| 970 | |
| 971 | if namespace is None: |
| 972 | namespace = {} |
| 973 | else: |
| 974 | # Copy namespace since we're going to mutate it. |
| 975 | namespace = namespace.copy() |
| 976 | |
Eric V. Smith | d138892 | 2018-01-07 14:30:17 -0500 | [diff] [blame] | 977 | anns = {} |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 978 | for item in fields: |
Eric V. Smith | ed7d429 | 2018-01-06 16:14:03 -0500 | [diff] [blame] | 979 | if isinstance(item, str): |
| 980 | name = item |
| 981 | tp = 'typing.Any' |
| 982 | elif len(item) == 2: |
| 983 | name, tp, = item |
| 984 | elif len(item) == 3: |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 985 | name, tp, spec = item |
| 986 | namespace[name] = spec |
Eric V. Smith | ed7d429 | 2018-01-06 16:14:03 -0500 | [diff] [blame] | 987 | anns[name] = tp |
| 988 | |
| 989 | namespace['__annotations__'] = anns |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 990 | cls = type(cls_name, bases, namespace) |
Eric V. Smith | d80b443 | 2018-01-06 17:09:58 -0500 | [diff] [blame] | 991 | return dataclass(cls, init=init, repr=repr, eq=eq, order=order, |
Eric V. Smith | dbf9cff | 2018-02-25 21:30:17 -0500 | [diff] [blame] | 992 | unsafe_hash=unsafe_hash, frozen=frozen) |
| 993 | |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 994 | |
| 995 | def replace(obj, **changes): |
| 996 | """Return a new object replacing specified fields with new values. |
| 997 | |
| 998 | This is especially useful for frozen classes. Example usage: |
| 999 | |
| 1000 | @dataclass(frozen=True) |
| 1001 | class C: |
| 1002 | x: int |
| 1003 | y: int |
| 1004 | |
| 1005 | c = C(1, 2) |
| 1006 | c1 = replace(c, x=3) |
| 1007 | assert c1.x == 3 and c1.y == 2 |
| 1008 | """ |
| 1009 | |
| 1010 | # We're going to mutate 'changes', but that's okay because it's a new |
| 1011 | # dict, even if called with 'replace(obj, **my_changes)'. |
| 1012 | |
Eric V. Smith | e7ba013 | 2018-01-06 12:41:53 -0500 | [diff] [blame] | 1013 | if not _is_dataclass_instance(obj): |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 1014 | raise TypeError("replace() should be called on dataclass instances") |
| 1015 | |
| 1016 | # It's an error to have init=False fields in 'changes'. |
| 1017 | # If a field is not in 'changes', read its value from the provided obj. |
| 1018 | |
Eric V. Smith | f199bc6 | 2018-03-18 20:40:34 -0400 | [diff] [blame] | 1019 | for f in getattr(obj, _FIELDS).values(): |
Eric V. Smith | f0db54a | 2017-12-04 16:58:55 -0500 | [diff] [blame] | 1020 | if not f.init: |
| 1021 | # Error if this field is specified in changes. |
| 1022 | if f.name in changes: |
| 1023 | raise ValueError(f'field {f.name} is declared with ' |
| 1024 | 'init=False, it cannot be specified with ' |
| 1025 | 'replace()') |
| 1026 | continue |
| 1027 | |
| 1028 | if f.name not in changes: |
| 1029 | changes[f.name] = getattr(obj, f.name) |
| 1030 | |
| 1031 | # Create the new object, which calls __init__() and __post_init__ |
| 1032 | # (if defined), using all of the init fields we've added and/or |
| 1033 | # left in 'changes'. |
| 1034 | # If there are values supplied in changes that aren't fields, this |
| 1035 | # will correctly raise a TypeError. |
| 1036 | return obj.__class__(**changes) |