Author formigacomcaimbra
Recipients eric.smith, formigacomcaimbra, python-dev
Date 2021-10-12.19:53:00
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
The objective of this feature is to add a way to omit fields of a dataclass when `asdict` or `astuple` is used.

The main propuse is to add the `hide` parameter in `field` and add it as an attribute in the `Field` class.
class User:
    name: str
    ws: WebSocket = field(hide=True)

user = User("NiumXp", None)
assert asdict(user) == {"name": "NiumXp"}
`asdict` will ignore all fields that have the `hide` attribute set as `True`.


Actually a possible solution to do it is doing this:
from dataclasses import *

_asdict = asdict

class WebSocket:

def asdict(obj):
    def factory(it):
        fields = []

        for raw_field in it:
            name, _ = raw_field

            field = obj.__dataclass_fields__[name]
            if not field.metadata.get("hide"):

        return dict(fields)
    return _asdict(obj, dict_factory=factory)

class User:
    name: str
    ws: WebSocket = field(metadata={"hide": True})

user = User("NiumXp", None)
assert asdict(user) == {"name": "NiumXp"}
We need to make the same in `astuple` and to avoid writing `field(metadata={"hide": True)` multiple times we can use

from functools import partial
from dataclasses import field as _field

field = _field(metadata={"hide": True})

But, this means that we can't reuse the `metadata` parameter.
Date User Action Args
2021-10-12 19:53:01formigacomcaimbrasetrecipients: + formigacomcaimbra, eric.smith, python-dev
2021-10-12 19:53:00formigacomcaimbrasetmessageid: <>
2021-10-12 19:53:00formigacomcaimbralinkissue45446 messages
2021-10-12 19:53:00formigacomcaimbracreate