Nium <[email protected]> added the comment:
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.
----------
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue45446>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com