python-attrs / python-attrs/cattrs
How to serialize (JSON) a type reference?
Open
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 1.1k
- Forks
- 159
- Avg merge
- 12h 21m
- Merged PRs (30d)
- 6
Description
(I know it's not a cattrs issue.)
I'm looking for a way to JSON-serialize a type-ref inside a attrs-class.
But type-refs aren't supported by json-lib.
See a litte example:
import attrs, cattrs, json
@attrs.mutable
class A:
my_type: type
@attrs.mutable
class B:
foo: int
a1=A(my_type=B)
a1u=cattrs.unstructure(a1)
a1uj=json.dumps(a1u)
Traceback (most recent call last):
File "C:\Python310\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "C:\Python310\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Python310\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python310\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Python310\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type type is not JSON serializable
Are there any ideas on how to achieve my goal?
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 example's cattrs.unstructure(a1) output and Python's json.dumps handling of type objects. Determine whether the requested behavior belongs in cattrs or in caller-side conversion; done should be a clear, documented and tested path for the desired serialization.
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
- Needs clarification
- Newbie friendliness
- 20/100