diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py index 1e98bf9b9bb97ba..21b66b7eb7dbd2a 100644 --- a/Lib/dataclasses.py +++ b/Lib/dataclasses.py @@ -260,6 +260,7 @@ class Field: 'compare', 'metadata', 'kw_only', + 'hide', '_field_type', # Private: not to be used by user code. ) @@ -277,6 +278,7 @@ def __init__(self, default, default_factory, init, repr, hash, compare, if metadata is None else types.MappingProxyType(metadata)) self.kw_only = kw_only + self.hide = hide self._field_type = None def __repr__(self): @@ -291,6 +293,7 @@ def __repr__(self): f'compare={self.compare!r},' f'metadata={self.metadata!r},' f'kw_only={self.kw_only!r},' + f'hide={self.hide!r}' f'_field_type={self._field_type}' ')') @@ -344,7 +347,8 @@ def __repr__(self): # so that a type checker can be told (via overloads) that this is a # function whose type depends on its parameters. def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, - hash=None, compare=True, metadata=None, kw_only=MISSING): + hash=None, compare=True, metadata=None, kw_only=MISSING, + hide=False): """Return an object to identify dataclass fields. default is the default value of the field. default_factory is a @@ -364,7 +368,7 @@ def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, if default is not MISSING and default_factory is not MISSING: raise ValueError('cannot specify both default and default_factory') return Field(default, default_factory, init, repr, hash, compare, - metadata, kw_only) + metadata, kw_only, hide) def _fields_in_init_order(fields): @@ -1236,6 +1240,8 @@ def _asdict_inner(obj, dict_factory): if _is_dataclass_instance(obj): result = [] for f in fields(obj): + if f.hide: + continue value = _asdict_inner(getattr(obj, f.name), dict_factory) result.append((f.name, value)) return dict_factory(result) @@ -1301,6 +1307,8 @@ def _astuple_inner(obj, tuple_factory): if _is_dataclass_instance(obj): result = [] for f in fields(obj): + if f.hide: + continue value = _astuple_inner(getattr(obj, f.name), tuple_factory) result.append(value) return tuple_factory(result)