Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

converters are not executed during fields assignment for classes created by attrs.make_class #1375

Open
ngchihuan opened this issue Nov 20, 2024 · 2 comments

Comments

@ngchihuan
Copy link

Hi @hynek,
I run into this problem with using converters for classes made by attrs.make_class.
Better explained with the following code.
Let me know if you need more information!

Python: 3.10
attrs version: 24.2.0

C = attrs.make_class("C",{"x": attrs.field(default=0, converter=int)})
C(x="0")
type(x) == int

However, converter is not applied when fields are assigned after the initialization.

C = attrs.make_class("C",{"x": attrs.field(default=0, converter=int)})
c= C()
c.x = "0"
type(c.x) == str
@hodgestar
Copy link

hodgestar commented Nov 20, 2024

Just noting that one can work around this by specifying on_setattr explicitly:

>>> from attrs import setters
>>> DEFAULT_SETATTR = setters.pipe(setters.convert, setters.validate)
>>> C = attrs.make_class("C",{"x": attrs.field(default=0, converter=int)}, on_setattr=DEFAULT_SETATTR)
>>> c = C("0")
>>> c.x
0
>>> c.x = "5"
>>> c.x

Although it took me a bit of digging in the source code to find that.

@hynek
Copy link
Member

hynek commented Nov 27, 2024

Unfortunately, that's not something we can change now anymore, so we'll improve the docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants