Message403756
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. |
|
Date |
User |
Action |
Args |
2021-10-12 19:53:01 | formigacomcaimbra | set | recipients:
+ formigacomcaimbra, eric.smith, python-dev |
2021-10-12 19:53:00 | formigacomcaimbra | set | messageid: <1634068380.97.0.117718217892.issue45446@roundup.psfhosted.org> |
2021-10-12 19:53:00 | formigacomcaimbra | link | issue45446 messages |
2021-10-12 19:53:00 | formigacomcaimbra | create | |
|