This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

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 <1634068380.97.0.117718217892.issue45446@roundup.psfhosted.org>
In-reply-to
Content
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.
```py
@dataclass
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:
```py
from dataclasses import *

_asdict = asdict


class WebSocket:
    pass


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"):
                fields.append(raw_field)

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


@dataclass
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

```py
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.
History
Date User Action Args
2021-10-12 19:53:01formigacomcaimbrasetrecipients: + formigacomcaimbra, eric.smith, python-dev
2021-10-12 19:53:00formigacomcaimbrasetmessageid: <1634068380.97.0.117718217892.issue45446@roundup.psfhosted.org>
2021-10-12 19:53:00formigacomcaimbralinkissue45446 messages
2021-10-12 19:53:00formigacomcaimbracreate