python-attrs / python-attrs/cattrs
Type validation on unstructure
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 1.1k
- Forks
- 159
- Avg merge
- 12h 21m
- Merged PRs (30d)
- 6
Description
- cattrs version: 23.1.2
- Python version: 3.11.5
- Operating System: gentoo
Description
I want users of my library to fill out an attrs class, then later I will unstructure it and send it out to a remote API. When the user creates the attrs instance, they can optionally use mypy to make sure they set the attributes to the correct types, but of course this is optional. Before I send out the data on the network I would like to be sure it matches the correct schema.
I know I could use attrs validators to enforce types in the attrs class, but I've found that its hard to do correctly for more advanced types. Before I send out the data on the network I would like to be sure it matches the correct schema.
However, it appears that cattrs doesn't check types in unstructure the same way structure does. Is there a way to make cattrs unstructure strictly, or perhaps the recommendation is to add separate validation after unstructuring?
What I Did
import attrs
import cattrs
@attrs.define
class Foo:
x: int = 42
f = Foo("wrong type")
print(cattrs.unstructure(f))
Actual output:
{'x': 'wrong type'}
Expected output: Exception
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the cattrs.unstructure entry point and the provided Foo example, then compare its behavior with structure. Define the expected strict-validation and exception behavior before implementing or documenting a resolution, and verify it against the wrong-type case.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100