3 ms·
I'm on board with wanting an alternative to dataclasses that's faster, doesn't require types, and is less noisy (having to put @dataclass on its own line before
by comex 3y ago
I'm on board with wanting an alternative to dataclasses that's faster, doesn't require types, and is less noisy (having to put @dataclass on its own line before every class is annoying when defining many small dataclasses).
But not having methods would produce APIs that feel really non-idiomatic. Essentially all Python types have methods, even immutable 'pure data' types. str has methods (though some things like `len` and regex search, which are methods in other languages, are functions in Python). int has methods (though they're rarely used). Immutable standard library classes – say, datetime or Path – have lots and lots of methods.
And inheritance… well, I could live without it but I've made good use of inheritance with dataclasses.
And as others have mentioned, the syntax is awkward.
I think my ideal solution would basically be dataclasses, but implemented in C and with more syntax sugar:
# Instead of "@dataclass\nclass Foo:"
struct Foo:
# Allow untyped fields:
x
# Make this do what you'd expect, instead of
# requiring "field(default_factory=list)":
y = []
# Of course, types are still allowed:
z: int = 0
Methods and inheritance would be allowed as usual.
It might be interesting if these structs acted as true value types, so that e.g. just assigning an instance from one variable to another would make a copy of all the fields. That way you could mutate the object without worrying about sharing. But arguably, having both value types and reference types would overcomplicate the mental model.