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
How to initialize an instance where all fields are default values? #1169
Comments
Python doesn't have the concept of zero values, so this is icky. But I suspect you could get this done with field hooks @sscherfke? |
I have implemented it via field hooks. def field_transformer(cls, fields):
new_fields = []
for field in fields:
if field.default is attrs.NOTHING:
new_fields.append(field.evolve(default=attrs.Factory(field.type)))
else:
new_fields.append(field)
return new_fields
@attrs.define(kw_only=True, field_transformer=field_transformer)
class Name:
first_name: str = attrs.field(default='')
last_name: str However, in the above example, I had to specify kw_only as true, otherwise I would get the following error:
I read the attrs code and found that the field_transformer is executed later than the default value checks.
|
Running over a similar issue. Would it be possible to use import typing
import attrs
@attrs.define
class MyClass:
a: int = 1
with attrs.field(converter = typing.Self):
b: str
c: list
The benefits I see:
|
How to initialize an instance where all fields are default values?
I don't want to add a default value to each field, and I want each field to automatically get a zero value by default.
This would make dataclass much like struct in the go language.
The text was updated successfully, but these errors were encountered: