classification
Title: Add a way to hide fields in dataclasses
Type: enhancement Stage: patch review
Components: Versions: Python 3.11
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: eric.smith Nosy List: eric.smith, formigacomcaimbra, python-dev
Priority: normal Keywords: patch

Created on 2021-10-12 15:23 by formigacomcaimbra, last changed 2021-10-13 16:12 by eric.smith.

Pull Requests
URL Status Linked Edit
PR 28904 open python-dev, 2021-10-12 15:25
Messages (3)
msg403749 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-10-12 18:46
Please explain what "hiding" does.
msg403756 - (view) Author: Nium (formigacomcaimbra) Date: 2021-10-12 19:53
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.
msg403845 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2021-10-13 16:12
"hide" is not a good name for this.

Does attrs have anything equivalent? This seems like a pretty niche usage, so I'm not inclined to include it without evidence of a wide-spread need for it.
History
Date User Action Args
2021-10-13 16:12:44eric.smithsetassignee: eric.smith
messages: + msg403845
2021-10-12 19:53:00formigacomcaimbrasetmessages: + msg403756
2021-10-12 18:46:53eric.smithsetnosy: + eric.smith
messages: + msg403749
2021-10-12 15:25:01python-devsetkeywords: + patch
nosy: + python-dev

pull_requests: + pull_request27195
stage: patch review
2021-10-12 15:23:21formigacomcaimbracreate