| 1 |
import re |
| 2 |
import sys |
| 3 |
import copy |
| 4 |
import types |
| 5 |
import inspect |
| 6 |
import keyword |
| 7 |
import builtins |
| 8 |
import functools |
| 9 |
import itertools |
| 10 |
import abc |
| 11 |
import _thread |
| 12 |
from types import FunctionType, GenericAlias |
| 13 |
|
| 14 |
|
| 15 |
__all__ = ['dataclass', |
| 16 |
'field', |
| 17 |
'Field', |
| 18 |
'FrozenInstanceError', |
| 19 |
'InitVar', |
| 20 |
'KW_ONLY', |
| 21 |
'MISSING', |
| 22 |
|
| 23 |
|
| 24 |
'fields', |
| 25 |
'asdict', |
| 26 |
'astuple', |
| 27 |
'make_dataclass', |
| 28 |
'replace', |
| 29 |
'is_dataclass', |
| 30 |
] |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
|
| 154 |
|
| 155 |
|
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
|
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
class FrozenInstanceError(AttributeError): pass |
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
class _HAS_DEFAULT_FACTORY_CLASS: |
| 179 |
def __repr__(self): |
| 180 |
return '<factory>' |
| 181 |
_HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS() |
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
class _MISSING_TYPE: |
| 186 |
pass |
| 187 |
MISSING = _MISSING_TYPE() |
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
class _KW_ONLY_TYPE: |
| 192 |
pass |
| 193 |
KW_ONLY = _KW_ONLY_TYPE() |
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
_EMPTY_METADATA = types.MappingProxyType({}) |
| 198 |
|
| 199 |
|
| 200 |
class _FIELD_BASE: |
| 201 |
def __init__(self, name): |
| 202 |
self.name = name |
| 203 |
def __repr__(self): |
| 204 |
return self.name |
| 205 |
_FIELD = _FIELD_BASE('_FIELD') |
| 206 |
_FIELD_CLASSVAR = _FIELD_BASE('_FIELD_CLASSVAR') |
| 207 |
_FIELD_INITVAR = _FIELD_BASE('_FIELD_INITVAR') |
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
_FIELDS = '__dataclass_fields__' |
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
_PARAMS = '__dataclass_params__' |
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
_POST_INIT_NAME = '__post_init__' |
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
_MODULE_IDENTIFIER_RE = re.compile(r'^(?:\s*(\w+)\s*\.)?\s*(\w+)') |
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
def _recursive_repr(user_function): |
| 229 |
|
| 230 |
|
| 231 |
repr_running = set() |
| 232 |
|
| 233 |
@functools.wraps(user_function) |
| 234 |
def wrapper(self): |
| 235 |
key = id(self), _thread.get_ident() |
| 236 |
if key in repr_running: |
| 237 |
return '...' |
| 238 |
repr_running.add(key) |
| 239 |
try: |
| 240 |
result = user_function(self) |
| 241 |
finally: |
| 242 |
repr_running.discard(key) |
| 243 |
return result |
| 244 |
return wrapper |
| 245 |
|
| 246 |
class InitVar: |
| 247 |
__slots__ = ('type', ) |
| 248 |
|
| 249 |
def __init__(self, type): |
| 250 |
self.type = type |
| 251 |
|
| 252 |
def __repr__(self): |
| 253 |
if isinstance(self.type, type): |
| 254 |
type_name = self.type.__name__ |
| 255 |
else: |
| 256 |
|
| 257 |
type_name = repr(self.type) |
| 258 |
return f'dataclasses.InitVar[{type_name}]' |
| 259 |
|
| 260 |
def __class_getitem__(cls, type): |
| 261 |
return InitVar(type) |
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
class Field: |
| 274 |
__slots__ = ('name', |
| 275 |
'type', |
| 276 |
'default', |
| 277 |
'default_factory', |
| 278 |
'repr', |
| 279 |
'hash', |
| 280 |
'init', |
| 281 |
'compare', |
| 282 |
'metadata', |
| 283 |
'kw_only', |
| 284 |
'_field_type', |
| 285 |
) |
| 286 |
|
| 287 |
def __init__(self, default, default_factory, init, repr, hash, compare, |
| 288 |
metadata, kw_only): |
| 289 |
self.name = None |
| 290 |
self.type = None |
| 291 |
self.default = default |
| 292 |
self.default_factory = default_factory |
| 293 |
self.init = init |
| 294 |
self.repr = repr |
| 295 |
self.hash = hash |
| 296 |
self.compare = compare |
| 297 |
self.metadata = (_EMPTY_METADATA |
| 298 |
if metadata is None else |
| 299 |
types.MappingProxyType(metadata)) |
| 300 |
self.kw_only = kw_only |
| 301 |
self._field_type = None |
| 302 |
|
| 303 |
@_recursive_repr |
| 304 |
def __repr__(self): |
| 305 |
return ('Field(' |
| 306 |
f'name={self.name!r},' |
| 307 |
f'type={self.type!r},' |
| 308 |
f'default={self.default!r},' |
| 309 |
f'default_factory={self.default_factory!r},' |
| 310 |
f'init={self.init!r},' |
| 311 |
f'repr={self.repr!r},' |
| 312 |
f'hash={self.hash!r},' |
| 313 |
f'compare={self.compare!r},' |
| 314 |
f'metadata={self.metadata!r},' |
| 315 |
f'kw_only={self.kw_only!r},' |
| 316 |
f'_field_type={self._field_type}' |
| 317 |
')') |
| 318 |
|
| 319 |
|
| 320 |
|
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
def __set_name__(self, owner, name): |
| 328 |
func = getattr(type(self.default), '__set_name__', None) |
| 329 |
if func: |
| 330 |
|
| 331 |
|
| 332 |
func(self.default, owner, name) |
| 333 |
|
| 334 |
__class_getitem__ = classmethod(GenericAlias) |
| 335 |
|
| 336 |
|
| 337 |
class _DataclassParams: |
| 338 |
__slots__ = ('init', |
| 339 |
'repr', |
| 340 |
'eq', |
| 341 |
'order', |
| 342 |
'unsafe_hash', |
| 343 |
'frozen', |
| 344 |
) |
| 345 |
|
| 346 |
def __init__(self, init, repr, eq, order, unsafe_hash, frozen): |
| 347 |
self.init = init |
| 348 |
self.repr = repr |
| 349 |
self.eq = eq |
| 350 |
self.order = order |
| 351 |
self.unsafe_hash = unsafe_hash |
| 352 |
self.frozen = frozen |
| 353 |
|
| 354 |
def __repr__(self): |
| 355 |
return ('_DataclassParams(' |
| 356 |
f'init={self.init!r},' |
| 357 |
f'repr={self.repr!r},' |
| 358 |
f'eq={self.eq!r},' |
| 359 |
f'order={self.order!r},' |
| 360 |
f'unsafe_hash={self.unsafe_hash!r},' |
| 361 |
f'frozen={self.frozen!r}' |
| 362 |
')') |
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, |
| 369 |
hash=None, compare=True, metadata=None, kw_only=MISSING): |
| 370 |
"""Return an object to identify dataclass fields. |
| 371 |
|
| 372 |
default is the default value of the field. default_factory is a |
| 373 |
0-argument function called to initialize a field's value. If init |
| 374 |
is true, the field will be a parameter to the class's __init__() |
| 375 |
function. If repr is true, the field will be included in the |
| 376 |
object's repr(). If hash is true, the field will be included in the |
| 377 |
object's hash(). If compare is true, the field will be used in |
| 378 |
comparison functions. metadata, if specified, must be a mapping |
| 379 |
which is stored but not otherwise examined by dataclass. If kw_only |
| 380 |
is true, the field will become a keyword-only parameter to |
| 381 |
__init__(). |
| 382 |
|
| 383 |
It is an error to specify both default and default_factory. |
| 384 |
""" |
| 385 |
|
| 386 |
if default is not MISSING and default_factory is not MISSING: |
| 387 |
raise ValueError('cannot specify both default and default_factory') |
| 388 |
return Field(default, default_factory, init, repr, hash, compare, |
| 389 |
metadata, kw_only) |
| 390 |
|
| 391 |
|
| 392 |
def _fields_in_init_order(fields): |
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
return (tuple(f for f in fields if f.init and not f.kw_only), |
| 397 |
tuple(f for f in fields if f.init and f.kw_only) |
| 398 |
) |
| 399 |
|
| 400 |
|
| 401 |
def _tuple_str(obj_name, fields): |
| 402 |
|
| 403 |
|
| 404 |
|
| 405 |
|
| 406 |
|
| 407 |
if not fields: |
| 408 |
return '()' |
| 409 |
|
| 410 |
return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)' |
| 411 |
|
| 412 |
|
| 413 |
def _create_fn(name, args, body, *, globals=None, locals=None, |
| 414 |
return_type=MISSING): |
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
if locals is None: |
| 419 |
locals = {} |
| 420 |
return_annotation = '' |
| 421 |
if return_type is not MISSING: |
| 422 |
locals['_return_type'] = return_type |
| 423 |
return_annotation = '->_return_type' |
| 424 |
args = ','.join(args) |
| 425 |
body = '\n'.join(f' {b}' for b in body) |
| 426 |
|
| 427 |
|
| 428 |
txt = f' def {name}({args}){return_annotation}:\n{body}' |
| 429 |
|
| 430 |
local_vars = ', '.join(locals.keys()) |
| 431 |
txt = f"def __create_fn__({local_vars}):\n{txt}\n return {name}" |
| 432 |
ns = {} |
| 433 |
exec(txt, globals, ns) |
| 434 |
return ns['__create_fn__'](**locals) |
| 435 |
|
| 436 |
|
| 437 |
def _field_assign(frozen, name, value, self_name): |
| 438 |
|
| 439 |
|
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
|
| 444 |
if frozen: |
| 445 |
return f'__dataclass_builtins_object__.__setattr__({self_name},{name!r},{value})' |
| 446 |
return f'{self_name}.{name}={value}' |
| 447 |
|
| 448 |
|
| 449 |
def _field_init(f, frozen, globals, self_name, slots): |
| 450 |
|
| 451 |
|
| 452 |
|
| 453 |
default_name = f'_dflt_{f.name}' |
| 454 |
if f.default_factory is not MISSING: |
| 455 |
if f.init: |
| 456 |
|
| 457 |
|
| 458 |
globals[default_name] = f.default_factory |
| 459 |
value = (f'{default_name}() ' |
| 460 |
f'if {f.name} is _HAS_DEFAULT_FACTORY ' |
| 461 |
f'else {f.name}') |
| 462 |
else: |
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
|
| 470 |
|
| 471 |
|
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
globals[default_name] = f.default_factory |
| 478 |
value = f'{default_name}()' |
| 479 |
else: |
| 480 |
|
| 481 |
if f.init: |
| 482 |
if f.default is MISSING: |
| 483 |
|
| 484 |
value = f.name |
| 485 |
elif f.default is not MISSING: |
| 486 |
globals[default_name] = f.default |
| 487 |
value = f.name |
| 488 |
else: |
| 489 |
|
| 490 |
if slots and f.default is not MISSING: |
| 491 |
globals[default_name] = f.default |
| 492 |
value = default_name |
| 493 |
else: |
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
return None |
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
|
| 502 |
if f._field_type is _FIELD_INITVAR: |
| 503 |
return None |
| 504 |
|
| 505 |
|
| 506 |
return _field_assign(frozen, f.name, value, self_name) |
| 507 |
|
| 508 |
|
| 509 |
def _init_param(f): |
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
|
| 514 |
if f.default is MISSING and f.default_factory is MISSING: |
| 515 |
|
| 516 |
|
| 517 |
default = '' |
| 518 |
elif f.default is not MISSING: |
| 519 |
|
| 520 |
|
| 521 |
default = f'=_dflt_{f.name}' |
| 522 |
elif f.default_factory is not MISSING: |
| 523 |
|
| 524 |
default = '=_HAS_DEFAULT_FACTORY' |
| 525 |
return f'{f.name}:_type_{f.name}{default}' |
| 526 |
|
| 527 |
|
| 528 |
def _init_fn(fields, std_fields, kw_only_fields, frozen, has_post_init, |
| 529 |
self_name, globals, slots): |
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
|
| 537 |
|
| 538 |
seen_default = False |
| 539 |
for f in std_fields: |
| 540 |
|
| 541 |
if f.init: |
| 542 |
if not (f.default is MISSING and f.default_factory is MISSING): |
| 543 |
seen_default = True |
| 544 |
elif seen_default: |
| 545 |
raise TypeError(f'non-default argument {f.name!r} ' |
| 546 |
'follows default argument') |
| 547 |
|
| 548 |
locals = {f'_type_{f.name}': f.type for f in fields} |
| 549 |
locals.update({ |
| 550 |
'MISSING': MISSING, |
| 551 |
'_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY, |
| 552 |
'__dataclass_builtins_object__': object, |
| 553 |
}) |
| 554 |
|
| 555 |
body_lines = [] |
| 556 |
for f in fields: |
| 557 |
line = _field_init(f, frozen, locals, self_name, slots) |
| 558 |
|
| 559 |
|
| 560 |
if line: |
| 561 |
body_lines.append(line) |
| 562 |
|
| 563 |
|
| 564 |
if has_post_init: |
| 565 |
params_str = ','.join(f.name for f in fields |
| 566 |
if f._field_type is _FIELD_INITVAR) |
| 567 |
body_lines.append(f'{self_name}.{_POST_INIT_NAME}({params_str})') |
| 568 |
|
| 569 |
|
| 570 |
if not body_lines: |
| 571 |
body_lines = ['pass'] |
| 572 |
|
| 573 |
_init_params = [_init_param(f) for f in std_fields] |
| 574 |
if kw_only_fields: |
| 575 |
|
| 576 |
|
| 577 |
|
| 578 |
_init_params += ['*'] |
| 579 |
_init_params += [_init_param(f) for f in kw_only_fields] |
| 580 |
return _create_fn('__init__', |
| 581 |
[self_name] + _init_params, |
| 582 |
body_lines, |
| 583 |
locals=locals, |
| 584 |
globals=globals, |
| 585 |
return_type=None) |
| 586 |
|
| 587 |
|
| 588 |
def _repr_fn(fields, globals): |
| 589 |
fn = _create_fn('__repr__', |
| 590 |
('self',), |
| 591 |
['return self.__class__.__qualname__ + f"(' + |
| 592 |
', '.join([f"{f.name}={{self.{f.name}!r}}" |
| 593 |
for f in fields]) + |
| 594 |
')"'], |
| 595 |
globals=globals) |
| 596 |
return _recursive_repr(fn) |
| 597 |
|
| 598 |
|
| 599 |
def _frozen_get_del_attr(cls, fields, globals): |
| 600 |
locals = {'cls': cls, |
| 601 |
'FrozenInstanceError': FrozenInstanceError} |
| 602 |
if fields: |
| 603 |
fields_str = '(' + ','.join(repr(f.name) for f in fields) + ',)' |
| 604 |
else: |
| 605 |
|
| 606 |
fields_str = '()' |
| 607 |
return (_create_fn('__setattr__', |
| 608 |
('self', 'name', 'value'), |
| 609 |
(f'if type(self) is cls or name in {fields_str}:', |
| 610 |
' raise FrozenInstanceError(f"cannot assign to field {name!r}")', |
| 611 |
f'super(cls, self).__setattr__(name, value)'), |
| 612 |
locals=locals, |
| 613 |
globals=globals), |
| 614 |
_create_fn('__delattr__', |
| 615 |
('self', 'name'), |
| 616 |
(f'if type(self) is cls or name in {fields_str}:', |
| 617 |
' raise FrozenInstanceError(f"cannot delete field {name!r}")', |
| 618 |
f'super(cls, self).__delattr__(name)'), |
| 619 |
locals=locals, |
| 620 |
globals=globals), |
| 621 |
) |
| 622 |
|
| 623 |
|
| 624 |
def _cmp_fn(name, op, self_tuple, other_tuple, globals): |
| 625 |
|
| 626 |
|
| 627 |
|
| 628 |
|
| 629 |
|
| 630 |
return _create_fn(name, |
| 631 |
('self', 'other'), |
| 632 |
[ 'if other.__class__ is self.__class__:', |
| 633 |
f' return {self_tuple}{op}{other_tuple}', |
| 634 |
'return NotImplemented'], |
| 635 |
globals=globals) |
| 636 |
|
| 637 |
|
| 638 |
def _hash_fn(fields, globals): |
| 639 |
self_tuple = _tuple_str('self', fields) |
| 640 |
return _create_fn('__hash__', |
| 641 |
('self',), |
| 642 |
[f'return hash({self_tuple})'], |
| 643 |
globals=globals) |
| 644 |
|
| 645 |
|
| 646 |
def _is_classvar(a_type, typing): |
| 647 |
|
| 648 |
|
| 649 |
return (a_type is typing.ClassVar |
| 650 |
or (type(a_type) is typing._GenericAlias |
| 651 |
and a_type.__origin__ is typing.ClassVar)) |
| 652 |
|
| 653 |
|
| 654 |
def _is_initvar(a_type, dataclasses): |
| 655 |
|
| 656 |
|
| 657 |
return (a_type is dataclasses.InitVar |
| 658 |
or type(a_type) is dataclasses.InitVar) |
| 659 |
|
| 660 |
def _is_kw_only(a_type, dataclasses): |
| 661 |
return a_type is dataclasses.KW_ONLY |
| 662 |
|
| 663 |
|
| 664 |
def _is_type(annotation, cls, a_module, a_type, is_type_predicate): |
| 665 |
|
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
|
| 671 |
|
| 672 |
|
| 673 |
|
| 674 |
|
| 675 |
|
| 676 |
|
| 677 |
|
| 678 |
|
| 679 |
|
| 680 |
|
| 681 |
|
| 682 |
|
| 683 |
|
| 684 |
|
| 685 |
|
| 686 |
|
| 687 |
|
| 688 |
|
| 689 |
|
| 690 |
|
| 691 |
|
| 692 |
|
| 693 |
|
| 694 |
|
| 695 |
|
| 696 |
|
| 697 |
|
| 698 |
|
| 699 |
|
| 700 |
|
| 701 |
|
| 702 |
|
| 703 |
|
| 704 |
|
| 705 |
match = _MODULE_IDENTIFIER_RE.match(annotation) |
| 706 |
if match: |
| 707 |
ns = None |
| 708 |
module_name = match.group(1) |
| 709 |
if not module_name: |
| 710 |
|
| 711 |
|
| 712 |
ns = sys.modules.get(cls.__module__).__dict__ |
| 713 |
else: |
| 714 |
|
| 715 |
module = sys.modules.get(cls.__module__) |
| 716 |
if module and module.__dict__.get(module_name) is a_module: |
| 717 |
ns = sys.modules.get(a_type.__module__).__dict__ |
| 718 |
if ns and is_type_predicate(ns.get(match.group(2)), a_module): |
| 719 |
return True |
| 720 |
return False |
| 721 |
|
| 722 |
|
| 723 |
def _get_field(cls, a_name, a_type, default_kw_only): |
| 724 |
|
| 725 |
|
| 726 |
|
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
default = getattr(cls, a_name, MISSING) |
| 732 |
if isinstance(default, Field): |
| 733 |
f = default |
| 734 |
else: |
| 735 |
if isinstance(default, types.MemberDescriptorType): |
| 736 |
|
| 737 |
default = MISSING |
| 738 |
f = field(default=default) |
| 739 |
|
| 740 |
|
| 741 |
f.name = a_name |
| 742 |
f.type = a_type |
| 743 |
|
| 744 |
|
| 745 |
|
| 746 |
|
| 747 |
f._field_type = _FIELD |
| 748 |
|
| 749 |
|
| 750 |
|
| 751 |
|
| 752 |
|
| 753 |
|
| 754 |
|
| 755 |
|
| 756 |
|
| 757 |
|
| 758 |
|
| 759 |
|
| 760 |
|
| 761 |
|
| 762 |
|
| 763 |
typing = sys.modules.get('typing') |
| 764 |
if typing: |
| 765 |
if (_is_classvar(a_type, typing) |
| 766 |
or (isinstance(f.type, str) |
| 767 |
and _is_type(f.type, cls, typing, typing.ClassVar, |
| 768 |
_is_classvar))): |
| 769 |
f._field_type = _FIELD_CLASSVAR |
| 770 |
|
| 771 |
|
| 772 |
|
| 773 |
if f._field_type is _FIELD: |
| 774 |
|
| 775 |
|
| 776 |
dataclasses = sys.modules[__name__] |
| 777 |
if (_is_initvar(a_type, dataclasses) |
| 778 |
or (isinstance(f.type, str) |
| 779 |
and _is_type(f.type, cls, dataclasses, dataclasses.InitVar, |
| 780 |
_is_initvar))): |
| 781 |
f._field_type = _FIELD_INITVAR |
| 782 |
|
| 783 |
|
| 784 |
|
| 785 |
|
| 786 |
|
| 787 |
|
| 788 |
if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR): |
| 789 |
if f.default_factory is not MISSING: |
| 790 |
raise TypeError(f'field {f.name} cannot have a ' |
| 791 |
'default factory') |
| 792 |
|
| 793 |
|
| 794 |
|
| 795 |
|
| 796 |
|
| 797 |
|
| 798 |
|
| 799 |
if f._field_type in (_FIELD, _FIELD_INITVAR): |
| 800 |
|
| 801 |
|
| 802 |
if f.kw_only is MISSING: |
| 803 |
f.kw_only = default_kw_only |
| 804 |
else: |
| 805 |
|
| 806 |
assert f._field_type is _FIELD_CLASSVAR |
| 807 |
if f.kw_only is not MISSING: |
| 808 |
raise TypeError(f'field {f.name} is a ClassVar but specifies ' |
| 809 |
'kw_only') |
| 810 |
|
| 811 |
|
| 812 |
|
| 813 |
|
| 814 |
if f._field_type is _FIELD and f.default.__class__.__hash__ is None: |
| 815 |
raise ValueError(f'mutable default {type(f.default)} for field ' |
| 816 |
f'{f.name} is not allowed: use default_factory') |
| 817 |
|
| 818 |
return f |
| 819 |
|
| 820 |
def _set_qualname(cls, value): |
| 821 |
|
| 822 |
|
| 823 |
if isinstance(value, FunctionType): |
| 824 |
value.__qualname__ = f"{cls.__qualname__}.{value.__name__}" |
| 825 |
return value |
| 826 |
|
| 827 |
def _set_new_attribute(cls, name, value): |
| 828 |
|
| 829 |
|
| 830 |
if name in cls.__dict__: |
| 831 |
return True |
| 832 |
_set_qualname(cls, value) |
| 833 |
setattr(cls, name, value) |
| 834 |
return False |
| 835 |
|
| 836 |
|
| 837 |
|
| 838 |
|
| 839 |
|
| 840 |
|
| 841 |
|
| 842 |
def _hash_set_none(cls, fields, globals): |
| 843 |
return None |
| 844 |
|
| 845 |
def _hash_add(cls, fields, globals): |
| 846 |
flds = [f for f in fields if (f.compare if f.hash is None else f.hash)] |
| 847 |
return _set_qualname(cls, _hash_fn(flds, globals)) |
| 848 |
|
| 849 |
def _hash_exception(cls, fields, globals): |
| 850 |
|
| 851 |
raise TypeError(f'Cannot overwrite attribute __hash__ ' |
| 852 |
f'in class {cls.__name__}') |
| 853 |
|
| 854 |
|
| 855 |
|
| 856 |
|
| 857 |
|
| 858 |
|
| 859 |
|
| 860 |
|
| 861 |
|
| 862 |
|
| 863 |
_hash_action = {(False, False, False, False): None, |
| 864 |
(False, False, False, True ): None, |
| 865 |
(False, False, True, False): None, |
| 866 |
(False, False, True, True ): None, |
| 867 |
(False, True, False, False): _hash_set_none, |
| 868 |
(False, True, False, True ): None, |
| 869 |
(False, True, True, False): _hash_add, |
| 870 |
(False, True, True, True ): None, |
| 871 |
(True, False, False, False): _hash_add, |
| 872 |
(True, False, False, True ): _hash_exception, |
| 873 |
(True, False, True, False): _hash_add, |
| 874 |
(True, False, True, True ): _hash_exception, |
| 875 |
(True, True, False, False): _hash_add, |
| 876 |
(True, True, False, True ): _hash_exception, |
| 877 |
(True, True, True, False): _hash_add, |
| 878 |
(True, True, True, True ): _hash_exception, |
| 879 |
} |
| 880 |
|
| 881 |
|
| 882 |
|
| 883 |
|
| 884 |
def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen, |
| 885 |
match_args, kw_only, slots, weakref_slot): |
| 886 |
|
| 887 |
|
| 888 |
|
| 889 |
|
| 890 |
fields = {} |
| 891 |
|
| 892 |
if cls.__module__ in sys.modules: |
| 893 |
globals = sys.modules[cls.__module__].__dict__ |
| 894 |
else: |
| 895 |
|
| 896 |
|
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
globals = {} |
| 901 |
|
| 902 |
setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order, |
| 903 |
unsafe_hash, frozen)) |
| 904 |
|
| 905 |
|
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
any_frozen_base = False |
| 910 |
has_dataclass_bases = False |
| 911 |
for b in cls.__mro__[-1:0:-1]: |
| 912 |
|
| 913 |
|
| 914 |
base_fields = getattr(b, _FIELDS, None) |
| 915 |
if base_fields is not None: |
| 916 |
has_dataclass_bases = True |
| 917 |
for f in base_fields.values(): |
| 918 |
fields[f.name] = f |
| 919 |
if getattr(b, _PARAMS).frozen: |
| 920 |
any_frozen_base = True |
| 921 |
|
| 922 |
|
| 923 |
|
| 924 |
|
| 925 |
|
| 926 |
|
| 927 |
|
| 928 |
|
| 929 |
|
| 930 |
|
| 931 |
|
| 932 |
|
| 933 |
|
| 934 |
cls_annotations = cls.__dict__.get('__annotations__', {}) |
| 935 |
|
| 936 |
|
| 937 |
|
| 938 |
|
| 939 |
cls_fields = [] |
| 940 |
|
| 941 |
KW_ONLY_seen = False |
| 942 |
dataclasses = sys.modules[__name__] |
| 943 |
for name, type in cls_annotations.items(): |
| 944 |
|
| 945 |
if (_is_kw_only(type, dataclasses) |
| 946 |
or (isinstance(type, str) |
| 947 |
and _is_type(type, cls, dataclasses, dataclasses.KW_ONLY, |
| 948 |
_is_kw_only))): |
| 949 |
|
| 950 |
|
| 951 |
if KW_ONLY_seen: |
| 952 |
raise TypeError(f'{name!r} is KW_ONLY, but KW_ONLY ' |
| 953 |
'has already been specified') |
| 954 |
KW_ONLY_seen = True |
| 955 |
kw_only = True |
| 956 |
else: |
| 957 |
|
| 958 |
cls_fields.append(_get_field(cls, name, type, kw_only)) |
| 959 |
|
| 960 |
for f in cls_fields: |
| 961 |
fields[f.name] = f |
| 962 |
|
| 963 |
|
| 964 |
|
| 965 |
|
| 966 |
|
| 967 |
if isinstance(getattr(cls, f.name, None), Field): |
| 968 |
if f.default is MISSING: |
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
|
| 974 |
|
| 975 |
delattr(cls, f.name) |
| 976 |
else: |
| 977 |
setattr(cls, f.name, f.default) |
| 978 |
|
| 979 |
|
| 980 |
for name, value in cls.__dict__.items(): |
| 981 |
if isinstance(value, Field) and not name in cls_annotations: |
| 982 |
raise TypeError(f'{name!r} is a field but has no type annotation') |
| 983 |
|
| 984 |
|
| 985 |
if has_dataclass_bases: |
| 986 |
|
| 987 |
if any_frozen_base and not frozen: |
| 988 |
raise TypeError('cannot inherit non-frozen dataclass from a ' |
| 989 |
'frozen one') |
| 990 |
|
| 991 |
|
| 992 |
if not any_frozen_base and frozen: |
| 993 |
raise TypeError('cannot inherit frozen dataclass from a ' |
| 994 |
'non-frozen one') |
| 995 |
|
| 996 |
|
| 997 |
|
| 998 |
setattr(cls, _FIELDS, fields) |
| 999 |
|
| 1000 |
|
| 1001 |
|
| 1002 |
|
| 1003 |
|
| 1004 |
|
| 1005 |
class_hash = cls.__dict__.get('__hash__', MISSING) |
| 1006 |
has_explicit_hash = not (class_hash is MISSING or |
| 1007 |
(class_hash is None and '__eq__' in cls.__dict__)) |
| 1008 |
|
| 1009 |
|
| 1010 |
|
| 1011 |
if order and not eq: |
| 1012 |
raise ValueError('eq must be true if order is true') |
| 1013 |
|
| 1014 |
|
| 1015 |
|
| 1016 |
|
| 1017 |
all_init_fields = [f for f in fields.values() |
| 1018 |
if f._field_type in (_FIELD, _FIELD_INITVAR)] |
| 1019 |
(std_init_fields, |
| 1020 |
kw_only_init_fields) = _fields_in_init_order(all_init_fields) |
| 1021 |
|
| 1022 |
if init: |
| 1023 |
|
| 1024 |
has_post_init = hasattr(cls, _POST_INIT_NAME) |
| 1025 |
|
| 1026 |
_set_new_attribute(cls, '__init__', |
| 1027 |
_init_fn(all_init_fields, |
| 1028 |
std_init_fields, |
| 1029 |
kw_only_init_fields, |
| 1030 |
frozen, |
| 1031 |
has_post_init, |
| 1032 |
|
| 1033 |
|
| 1034 |
|
| 1035 |
'__dataclass_self__' if 'self' in fields |
| 1036 |
else 'self', |
| 1037 |
globals, |
| 1038 |
slots, |
| 1039 |
)) |
| 1040 |
|
| 1041 |
|
| 1042 |
|
| 1043 |
field_list = [f for f in fields.values() if f._field_type is _FIELD] |
| 1044 |
|
| 1045 |
if repr: |
| 1046 |
flds = [f for f in field_list if f.repr] |
| 1047 |
_set_new_attribute(cls, '__repr__', _repr_fn(flds, globals)) |
| 1048 |
|
| 1049 |
if eq: |
| 1050 |
|
| 1051 |
|
| 1052 |
flds = [f for f in field_list if f.compare] |
| 1053 |
self_tuple = _tuple_str('self', flds) |
| 1054 |
other_tuple = _tuple_str('other', flds) |
| 1055 |
_set_new_attribute(cls, '__eq__', |
| 1056 |
_cmp_fn('__eq__', '==', |
| 1057 |
self_tuple, other_tuple, |
| 1058 |
globals=globals)) |
| 1059 |
|
| 1060 |
if order: |
| 1061 |
|
| 1062 |
flds = [f for f in field_list if f.compare] |
| 1063 |
self_tuple = _tuple_str('self', flds) |
| 1064 |
other_tuple = _tuple_str('other', flds) |
| 1065 |
for name, op in [('__lt__', '<'), |
| 1066 |
('__le__', '<='), |
| 1067 |
('__gt__', '>'), |
| 1068 |
('__ge__', '>='), |
| 1069 |
]: |
| 1070 |
if _set_new_attribute(cls, name, |
| 1071 |
_cmp_fn(name, op, self_tuple, other_tuple, |
| 1072 |
globals=globals)): |
| 1073 |
raise TypeError(f'Cannot overwrite attribute {name} ' |
| 1074 |
f'in class {cls.__name__}. Consider using ' |
| 1075 |
'functools.total_ordering') |
| 1076 |
|
| 1077 |
if frozen: |
| 1078 |
for fn in _frozen_get_del_attr(cls, field_list, globals): |
| 1079 |
if _set_new_attribute(cls, fn.__name__, fn): |
| 1080 |
raise TypeError(f'Cannot overwrite attribute {fn.__name__} ' |
| 1081 |
f'in class {cls.__name__}') |
| 1082 |
|
| 1083 |
|
| 1084 |
hash_action = _hash_action[bool(unsafe_hash), |
| 1085 |
bool(eq), |
| 1086 |
bool(frozen), |
| 1087 |
has_explicit_hash] |
| 1088 |
if hash_action: |
| 1089 |
|
| 1090 |
|
| 1091 |
cls.__hash__ = hash_action(cls, field_list, globals) |
| 1092 |
|
| 1093 |
if not getattr(cls, '__doc__'): |
| 1094 |
|
| 1095 |
try: |
| 1096 |
|
| 1097 |
|
| 1098 |
text_sig = str(inspect.signature(cls)).replace(' -> None', '') |
| 1099 |
except (TypeError, ValueError): |
| 1100 |
text_sig = '' |
| 1101 |
cls.__doc__ = (cls.__name__ + text_sig) |
| 1102 |
|
| 1103 |
if match_args: |
| 1104 |
|
| 1105 |
_set_new_attribute(cls, '__match_args__', |
| 1106 |
tuple(f.name for f in std_init_fields)) |
| 1107 |
|
| 1108 |
|
| 1109 |
if weakref_slot and not slots: |
| 1110 |
raise TypeError('weakref_slot is True but slots is False') |
| 1111 |
if slots: |
| 1112 |
cls = _add_slots(cls, frozen, weakref_slot) |
| 1113 |
|
| 1114 |
abc.update_abstractmethods(cls) |
| 1115 |
|
| 1116 |
return cls |
| 1117 |
|
| 1118 |
|
| 1119 |
|
| 1120 |
|
| 1121 |
|
| 1122 |
|
| 1123 |
def _dataclass_getstate(self): |
| 1124 |
return [getattr(self, f.name) for f in fields(self)] |
| 1125 |
|
| 1126 |
|
| 1127 |
def _dataclass_setstate(self, state): |
| 1128 |
for field, value in zip(fields(self), state): |
| 1129 |
|
| 1130 |
object.__setattr__(self, field.name, value) |
| 1131 |
|
| 1132 |
|
| 1133 |
def _get_slots(cls): |
| 1134 |
match cls.__dict__.get('__slots__'): |
| 1135 |
|
| 1136 |
|
| 1137 |
case None: |
| 1138 |
yield from ('__dict__', '__weakref__') |
| 1139 |
case str(slot): |
| 1140 |
yield slot |
| 1141 |
|
| 1142 |
|
| 1143 |
case iterable if not hasattr(iterable, '__next__'): |
| 1144 |
yield from iterable |
| 1145 |
case _: |
| 1146 |
raise TypeError(f"Slots of '{cls.__name__}' cannot be determined") |
| 1147 |
|
| 1148 |
|
| 1149 |
def _add_slots(cls, is_frozen, weakref_slot): |
| 1150 |
|
| 1151 |
|
| 1152 |
|
| 1153 |
|
| 1154 |
if '__slots__' in cls.__dict__: |
| 1155 |
raise TypeError(f'{cls.__name__} already specifies __slots__') |
| 1156 |
|
| 1157 |
|
| 1158 |
cls_dict = dict(cls.__dict__) |
| 1159 |
field_names = tuple(f.name for f in fields(cls)) |
| 1160 |
|
| 1161 |
inherited_slots = set( |
| 1162 |
itertools.chain.from_iterable(map(_get_slots, cls.__mro__[1:-1])) |
| 1163 |
) |
| 1164 |
|
| 1165 |
|
| 1166 |
cls_dict["__slots__"] = tuple( |
| 1167 |
itertools.filterfalse( |
| 1168 |
inherited_slots.__contains__, |
| 1169 |
itertools.chain( |
| 1170 |
|
| 1171 |
|
| 1172 |
field_names, ('__weakref__',) if weakref_slot else () |
| 1173 |
) |
| 1174 |
), |
| 1175 |
) |
| 1176 |
|
| 1177 |
for field_name in field_names: |
| 1178 |
|
| 1179 |
|
| 1180 |
cls_dict.pop(field_name, None) |
| 1181 |
|
| 1182 |
|
| 1183 |
cls_dict.pop('__dict__', None) |
| 1184 |
|
| 1185 |
|
| 1186 |
cls_dict.pop('__weakref__', None) |
| 1187 |
|
| 1188 |
|
| 1189 |
qualname = getattr(cls, '__qualname__', None) |
| 1190 |
cls = type(cls)(cls.__name__, cls.__bases__, cls_dict) |
| 1191 |
if qualname is not None: |
| 1192 |
cls.__qualname__ = qualname |
| 1193 |
|
| 1194 |
if is_frozen: |
| 1195 |
|
| 1196 |
if '__getstate__' not in cls_dict: |
| 1197 |
cls.__getstate__ = _dataclass_getstate |
| 1198 |
if '__setstate__' not in cls_dict: |
| 1199 |
cls.__setstate__ = _dataclass_setstate |
| 1200 |
|
| 1201 |
return cls |
| 1202 |
|
| 1203 |
|
| 1204 |
def dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, |
| 1205 |
unsafe_hash=False, frozen=False, match_args=True, |
| 1206 |
kw_only=False, slots=False, weakref_slot=False): |
| 1207 |
"""Add dunder methods based on the fields defined in the class. |
| 1208 |
|
| 1209 |
Examines PEP 526 __annotations__ to determine fields. |
| 1210 |
|
| 1211 |
If init is true, an __init__() method is added to the class. If repr |
| 1212 |
is true, a __repr__() method is added. If order is true, rich |
| 1213 |
comparison dunder methods are added. If unsafe_hash is true, a |
| 1214 |
__hash__() method is added. If frozen is true, fields may not be |
| 1215 |
assigned to after instance creation. If match_args is true, the |
| 1216 |
__match_args__ tuple is added. If kw_only is true, then by default |
| 1217 |
all fields are keyword-only. If slots is true, a new class with a |
| 1218 |
__slots__ attribute is returned. |
| 1219 |
""" |
| 1220 |
|
| 1221 |
def wrap(cls): |
| 1222 |
return _process_class(cls, init, repr, eq, order, unsafe_hash, |
| 1223 |
frozen, match_args, kw_only, slots, |
| 1224 |
weakref_slot) |
| 1225 |
|
| 1226 |
|
| 1227 |
if cls is None: |
| 1228 |
|
| 1229 |
return wrap |
| 1230 |
|
| 1231 |
|
| 1232 |
return wrap(cls) |
| 1233 |
|
| 1234 |
|
| 1235 |
def fields(class_or_instance): |
| 1236 |
"""Return a tuple describing the fields of this dataclass. |
| 1237 |
|
| 1238 |
Accepts a dataclass or an instance of one. Tuple elements are of |
| 1239 |
type Field. |
| 1240 |
""" |
| 1241 |
|
| 1242 |
|
| 1243 |
try: |
| 1244 |
fields = getattr(class_or_instance, _FIELDS) |
| 1245 |
except AttributeError: |
| 1246 |
raise TypeError('must be called with a dataclass type or instance') from None |
| 1247 |
|
| 1248 |
|
| 1249 |
|
| 1250 |
return tuple(f for f in fields.values() if f._field_type is _FIELD) |
| 1251 |
|
| 1252 |
|
| 1253 |
def _is_dataclass_instance(obj): |
| 1254 |
"""Returns True if obj is an instance of a dataclass.""" |
| 1255 |
return hasattr(type(obj), _FIELDS) |
| 1256 |
|
| 1257 |
|
| 1258 |
def is_dataclass(obj): |
| 1259 |
"""Returns True if obj is a dataclass or an instance of a |
| 1260 |
dataclass.""" |
| 1261 |
cls = obj if isinstance(obj, type) else type(obj) |
| 1262 |
return hasattr(cls, _FIELDS) |
| 1263 |
|
| 1264 |
|
| 1265 |
def asdict(obj, *, dict_factory=dict): |
| 1266 |
"""Return the fields of a dataclass instance as a new dictionary mapping |
| 1267 |
field names to field values. |
| 1268 |
|
| 1269 |
Example usage:: |
| 1270 |
|
| 1271 |
@dataclass |
| 1272 |
class C: |
| 1273 |
x: int |
| 1274 |
y: int |
| 1275 |
|
| 1276 |
c = C(1, 2) |
| 1277 |
assert asdict(c) == {'x': 1, 'y': 2} |
| 1278 |
|
| 1279 |
If given, 'dict_factory' will be used instead of built-in dict. |
| 1280 |
The function applies recursively to field values that are |
| 1281 |
dataclass instances. This will also look into built-in containers: |
| 1282 |
tuples, lists, and dicts. |
| 1283 |
""" |
| 1284 |
if not _is_dataclass_instance(obj): |
| 1285 |
raise TypeError("asdict() should be called on dataclass instances") |
| 1286 |
return _asdict_inner(obj, dict_factory) |
| 1287 |
|
| 1288 |
|
| 1289 |
def _asdict_inner(obj, dict_factory): |
| 1290 |
if _is_dataclass_instance(obj): |
| 1291 |
result = [] |
| 1292 |
for f in fields(obj): |
| 1293 |
value = _asdict_inner(getattr(obj, f.name), dict_factory) |
| 1294 |
result.append((f.name, value)) |
| 1295 |
return dict_factory(result) |
| 1296 |
elif isinstance(obj, tuple) and hasattr(obj, '_fields'): |
| 1297 |
|
| 1298 |
|
| 1299 |
|
| 1300 |
|
| 1301 |
|
| 1302 |
|
| 1303 |
|
| 1304 |
|
| 1305 |
|
| 1306 |
|
| 1307 |
|
| 1308 |
|
| 1309 |
|
| 1310 |
|
| 1311 |
|
| 1312 |
|
| 1313 |
|
| 1314 |
|
| 1315 |
|
| 1316 |
return type(obj)(*[_asdict_inner(v, dict_factory) for v in obj]) |
| 1317 |
elif isinstance(obj, (list, tuple)): |
| 1318 |
|
| 1319 |
|
| 1320 |
|
| 1321 |
return type(obj)(_asdict_inner(v, dict_factory) for v in obj) |
| 1322 |
elif isinstance(obj, dict): |
| 1323 |
return type(obj)((_asdict_inner(k, dict_factory), |
| 1324 |
_asdict_inner(v, dict_factory)) |
| 1325 |
for k, v in obj.items()) |
| 1326 |
else: |
| 1327 |
return copy.deepcopy(obj) |
| 1328 |
|
| 1329 |
|
| 1330 |
def astuple(obj, *, tuple_factory=tuple): |
| 1331 |
"""Return the fields of a dataclass instance as a new tuple of field values. |
| 1332 |
|
| 1333 |
Example usage:: |
| 1334 |
|
| 1335 |
@dataclass |
| 1336 |
class C: |
| 1337 |
x: int |
| 1338 |
y: int |
| 1339 |
|
| 1340 |
c = C(1, 2) |
| 1341 |
assert astuple(c) == (1, 2) |
| 1342 |
|
| 1343 |
If given, 'tuple_factory' will be used instead of built-in tuple. |
| 1344 |
The function applies recursively to field values that are |
| 1345 |
dataclass instances. This will also look into built-in containers: |
| 1346 |
tuples, lists, and dicts. |
| 1347 |
""" |
| 1348 |
|
| 1349 |
if not _is_dataclass_instance(obj): |
| 1350 |
raise TypeError("astuple() should be called on dataclass instances") |
| 1351 |
return _astuple_inner(obj, tuple_factory) |
| 1352 |
|
| 1353 |
|
| 1354 |
def _astuple_inner(obj, tuple_factory): |
| 1355 |
if _is_dataclass_instance(obj): |
| 1356 |
result = [] |
| 1357 |
for f in fields(obj): |
| 1358 |
value = _astuple_inner(getattr(obj, f.name), tuple_factory) |
| 1359 |
result.append(value) |
| 1360 |
return tuple_factory(result) |
| 1361 |
elif isinstance(obj, tuple) and hasattr(obj, '_fields'): |
| 1362 |
|
| 1363 |
|
| 1364 |
|
| 1365 |
|
| 1366 |
|
| 1367 |
|
| 1368 |
return type(obj)(*[_astuple_inner(v, tuple_factory) for v in obj]) |
| 1369 |
elif isinstance(obj, (list, tuple)): |
| 1370 |
|
| 1371 |
|
| 1372 |
|
| 1373 |
return type(obj)(_astuple_inner(v, tuple_factory) for v in obj) |
| 1374 |
elif isinstance(obj, dict): |
| 1375 |
return type(obj)((_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory)) |
| 1376 |
for k, v in obj.items()) |
| 1377 |
else: |
| 1378 |
return copy.deepcopy(obj) |
| 1379 |
|
| 1380 |
|
| 1381 |
def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, |
| 1382 |
repr=True, eq=True, order=False, unsafe_hash=False, |
| 1383 |
frozen=False, match_args=True, kw_only=False, slots=False, |
| 1384 |
weakref_slot=False): |
| 1385 |
"""Return a new dynamically created dataclass. |
| 1386 |
|
| 1387 |
The dataclass name will be 'cls_name'. 'fields' is an iterable |
| 1388 |
of either (name), (name, type) or (name, type, Field) objects. If type is |
| 1389 |
omitted, use the string 'typing.Any'. Field objects are created by |
| 1390 |
the equivalent of calling 'field(name, type [, Field-info])'.:: |
| 1391 |
|
| 1392 |
C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,)) |
| 1393 |
|
| 1394 |
is equivalent to:: |
| 1395 |
|
| 1396 |
@dataclass |
| 1397 |
class C(Base): |
| 1398 |
x: 'typing.Any' |
| 1399 |
y: int |
| 1400 |
z: int = field(init=False) |
| 1401 |
|
| 1402 |
For the bases and namespace parameters, see the builtin type() function. |
| 1403 |
|
| 1404 |
The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to |
| 1405 |
dataclass(). |
| 1406 |
""" |
| 1407 |
|
| 1408 |
if namespace is None: |
| 1409 |
namespace = {} |
| 1410 |
|
| 1411 |
|
| 1412 |
|
| 1413 |
seen = set() |
| 1414 |
annotations = {} |
| 1415 |
defaults = {} |
| 1416 |
for item in fields: |
| 1417 |
if isinstance(item, str): |
| 1418 |
name = item |
| 1419 |
tp = 'typing.Any' |
| 1420 |
elif len(item) == 2: |
| 1421 |
name, tp, = item |
| 1422 |
elif len(item) == 3: |
| 1423 |
name, tp, spec = item |
| 1424 |
defaults[name] = spec |
| 1425 |
else: |
| 1426 |
raise TypeError(f'Invalid field: {item!r}') |
| 1427 |
|
| 1428 |
if not isinstance(name, str) or not name.isidentifier(): |
| 1429 |
raise TypeError(f'Field names must be valid identifiers: {name!r}') |
| 1430 |
if keyword.iskeyword(name): |
| 1431 |
raise TypeError(f'Field names must not be keywords: {name!r}') |
| 1432 |
if name in seen: |
| 1433 |
raise TypeError(f'Field name duplicated: {name!r}') |
| 1434 |
|
| 1435 |
seen.add(name) |
| 1436 |
annotations[name] = tp |
| 1437 |
|
| 1438 |
|
| 1439 |
def exec_body_callback(ns): |
| 1440 |
ns.update(namespace) |
| 1441 |
ns.update(defaults) |
| 1442 |
ns['__annotations__'] = annotations |
| 1443 |
|
| 1444 |
|
| 1445 |
|
| 1446 |
cls = types.new_class(cls_name, bases, {}, exec_body_callback) |
| 1447 |
|
| 1448 |
|
| 1449 |
return dataclass(cls, init=init, repr=repr, eq=eq, order=order, |
| 1450 |
unsafe_hash=unsafe_hash, frozen=frozen, |
| 1451 |
match_args=match_args, kw_only=kw_only, slots=slots, |
| 1452 |
weakref_slot=weakref_slot) |
| 1453 |
|
| 1454 |
|
| 1455 |
def replace(obj, /, **changes): |
| 1456 |
"""Return a new object replacing specified fields with new values. |
| 1457 |
|
| 1458 |
This is especially useful for frozen classes. Example usage:: |
| 1459 |
|
| 1460 |
@dataclass(frozen=True) |
| 1461 |
class C: |
| 1462 |
x: int |
| 1463 |
y: int |
| 1464 |
|
| 1465 |
c = C(1, 2) |
| 1466 |
c1 = replace(c, x=3) |
| 1467 |
assert c1.x == 3 and c1.y == 2 |
| 1468 |
""" |
| 1469 |
|
| 1470 |
|
| 1471 |
|
| 1472 |
|
| 1473 |
if not _is_dataclass_instance(obj): |
| 1474 |
raise TypeError("replace() should be called on dataclass instances") |
| 1475 |
|
| 1476 |
|
| 1477 |
|
| 1478 |
|
| 1479 |
for f in getattr(obj, _FIELDS).values(): |
| 1480 |
|
| 1481 |
if f._field_type is _FIELD_CLASSVAR: |
| 1482 |
continue |
| 1483 |
|
| 1484 |
if not f.init: |
| 1485 |
|
| 1486 |
if f.name in changes: |
| 1487 |
raise ValueError(f'field {f.name} is declared with ' |
| 1488 |
'init=False, it cannot be specified with ' |
| 1489 |
'replace()') |
| 1490 |
continue |
| 1491 |
|
| 1492 |
if f.name not in changes: |
| 1493 |
if f._field_type is _FIELD_INITVAR and f.default is MISSING: |
| 1494 |
raise ValueError(f"InitVar {f.name!r} " |
| 1495 |
'must be specified with replace()') |
| 1496 |
changes[f.name] = getattr(obj, f.name) |
| 1497 |
|
| 1498 |
|
| 1499 |
|
| 1500 |
|
| 1501 |
|
| 1502 |
|
| 1503 |
return obj.__class__(**changes) |