Return a new dynamically created dataclass. The dataclass name will be 'cls_name'. 'fields' is an iterable of either (name), (name, type) or (name, type, Field) objects. If type is omitted, use the string 'typing.Any'. Field objects are created by the equivalent of calling 'field(
(cls_name, fields, *, bases=(), namespace=None, init=True,
repr=True, eq=True, order=False, unsafe_hash=False,
frozen=False, match_args=True, kw_only=False, slots=False,
weakref_slot=False, module=None, decorator=dataclass)
| 1626 | |
| 1627 | |
| 1628 | def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, |
| 1629 | repr=True, eq=True, order=False, unsafe_hash=False, |
| 1630 | frozen=False, match_args=True, kw_only=False, slots=False, |
| 1631 | weakref_slot=False, module=None, decorator=dataclass): |
| 1632 | """Return a new dynamically created dataclass. |
| 1633 | |
| 1634 | The dataclass name will be 'cls_name'. 'fields' is an iterable |
| 1635 | of either (name), (name, type) or (name, type, Field) objects. If type is |
| 1636 | omitted, use the string 'typing.Any'. Field objects are created by |
| 1637 | the equivalent of calling 'field(name, type [, Field-info])'.:: |
| 1638 | |
| 1639 | C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,)) |
| 1640 | |
| 1641 | is equivalent to:: |
| 1642 | |
| 1643 | @dataclass |
| 1644 | class C(Base): |
| 1645 | x: 'typing.Any' |
| 1646 | y: int |
| 1647 | z: int = field(init=False) |
| 1648 | |
| 1649 | For the bases and namespace parameters, see the builtin type() function. |
| 1650 | |
| 1651 | The parameters init, repr, eq, order, unsafe_hash, frozen, match_args, kw_only, |
| 1652 | slots, and weakref_slot are passed to dataclass(). |
| 1653 | |
| 1654 | If module parameter is defined, the '__module__' attribute of the dataclass is |
| 1655 | set to that value. |
| 1656 | """ |
| 1657 | |
| 1658 | if namespace is None: |
| 1659 | namespace = {} |
| 1660 | |
| 1661 | # While we're looking through the field names, validate that they |
| 1662 | # are identifiers, are not keywords, and not duplicates. |
| 1663 | seen = set() |
| 1664 | annotations = {} |
| 1665 | defaults = {} |
| 1666 | for item in fields: |
| 1667 | if isinstance(item, str): |
| 1668 | name = item |
| 1669 | tp = _ANY_MARKER |
| 1670 | elif len(item) == 2: |
| 1671 | name, tp, = item |
| 1672 | elif len(item) == 3: |
| 1673 | name, tp, spec = item |
| 1674 | defaults[name] = spec |
| 1675 | else: |
| 1676 | raise TypeError(f'Invalid field: {item!r}') |
| 1677 | |
| 1678 | if not isinstance(name, str) or not name.isidentifier(): |
| 1679 | raise TypeError(f'Field names must be valid identifiers: {name!r}') |
| 1680 | if keyword.iskeyword(name): |
| 1681 | raise TypeError(f'Field names must not be keywords: {name!r}') |
| 1682 | if name in seen: |
| 1683 | raise TypeError(f'Field name duplicated: {name!r}') |
| 1684 | |
| 1685 | seen.add(name) |
searching dependent graphs…