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