Comments (3)
Howdy!
Yeah, like you've noticed, cattrs skips init=False
fields by default.
This can be changed on a case-by-case basis by generating and registering an unstructure hook for a class.
from cattrs import Converter
from cattrs.gen import make_dict_unstructure_fn
def test_class_with_init_false():
foo = ClassWithInitFalse(a=1, b="b")
conv = cattrs.Converter()
conv.register_unstructure_hook(
ClassWithInitFalse,
make_dict_unstructure_fn(
ClassWithInitFalse, conv, _cattrs_include_init_false=True
),
)
serialized = conv.unstructure(foo)
assert serialized == {"a": 1, "b": "b", "d": 2}
This can be applied wider (for example, to all attrs classes) using a hook factory that's similar to this. That's a little more complex but I can show you how if you need to.
I'm going to close this now to keep the issue list tidy, let me know if you have further questions!
from cattrs.
Thanks @Tinche for the reply.
Yes, I’d like to enable it for all classes in my app. (Out of curiosity; why is it not enabled by default for all?)
So I’d appreciate if you show how it can be done (or point me to docs if there’s any for this)
Thanks.
from cattrs.
Yes, I’d like to enable it for all classes in my app.
Instead of a single unstructure hook for ClassWithInitFalse
, we're going to define an unstructure hook factory for all attrs classes. Here's the code, it looks somewhat similar to the single-class case:
from attrs import field, frozen, has
import cattrs
from cattrs.gen import make_dict_unstructure_fn
@frozen
class ClassWithInitFalse:
a: int
b: str
d: int = field(init=False, default=2)
def test_class_with_init_false():
foo = ClassWithInitFalse(a=1, b="b")
conv = cattrs.Converter()
conv.register_unstructure_hook_factory(
has,
lambda t: make_dict_unstructure_fn(t, conv, _cattrs_include_init_false=True),
)
serialized = conv.unstructure(foo)
assert serialized == {"a": 1, "b": "b", "d": 2}
(Out of curiosity; why is it not enabled by default for all?)
I find folks usually use init=False
attributes for computed attributes that get set in __attrs_post_init__
.
point me to docs if there’s any for this
I guess we don't have exact docs for this, but you can look at https://catt.rs/en/latest/usage.html#using-factory-hooks for a larger example for customizing attrs handling using factory hooks.
from cattrs.
Related Issues (20)
- Dataclass structuring fails with misleading error message.
- Default field conversion conflicts with user-defined field converter function HOT 3
- [macOS] Error when trying to run tests: `ImportError: cannot import name 'CodecOptions' from 'bson'` HOT 2
- How to hook into structuring of a simple dict? HOT 6
- Incorrect dispatch in Python 3.12 HOT 4
- Why does structuring of datetime in attrs class need a structure hook? HOT 1
- `prefer_attrib_converters` doesn't work when the field is aliased HOT 2
- Register structure hook only for optional types HOT 2
- TYPE_CHECKING and init=False HOT 5
- Problem with tagged union example HOT 3
- Subclass disambiguation for nested structures. HOT 3
- Unstructuring generics HOT 5
- Inheriting overrides HOT 3
- 23.2.3: test suite fails with pytest 8.2.1 HOT 5
- Register multiple hooks for a class HOT 3
- Nested class structure HOT 4
- Derived class disambiguating fails, but only sometimes. HOT 4
- Calling `include_subclasses()` prevents later structure hooks from working HOT 1
- Python 3.13.0b2: 4 tests failuires HOT 5
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from cattrs.