Dataclass bindable attributes #3957
Replies: 1 comment 3 replies
-
Thanks for sharing this idea, @balex89! Here's a slightly refined version I came up with: def bindable_dataclass(dcls: type) -> type:
if not dataclasses.is_dataclass(dcls):
raise ValueError('Only dataclasses are supported')
for field in dataclasses.fields(dcls):
p = binding.BindableProperty()
p.__set_name__(dcls, field.name)
setattr(dcls, field.name, p)
return dcls
For picking individual attributes, I wonder if we can provide something like a @dataclasses.dataclass
class MyClass:
x: float = 0.0
y: float = binding.bindable_field(0.0) But I'm not sure about the best API. It might depend on the application. I wonder if there are any more unwanted side effects. One last thing to consider might be performance: The decorator appears so convenient that users might want to add it to many classes to make them bindable - just in case. This adds a small overhead to every value assignment which might add up for large data structures. On the other hand, using bindings without care can decrease performance anyway. |
Beta Was this translation helpful? Give feedback.
-
It seems handy to make a
@dataclasses.dataclass
attribute bindable. Unfortunately, there is no clear way to achieve it by following the documentation instructions onbinding.BindableProperty
as it conflictsdataclass
definition with default values (ordataclass.field()
function) :Fortunately, once constructed,
dataclass
is not much different from typical user defined class, so one possible approach is to add bindable properties retroactively:Then use this as decorator:
One might want to be able to pick specific attributes only:
One minor drawback to consider is losing access to default values through class attributes (
MyClass.b
). That doesn't seem to break any common use case though.Also, this trick doesn't quite work with FastAPI-compatible pydantic dataclasses and might demand a little more effort.
Yet, overall, in my opinion it looks like an easy-to-implement useful out-of-the-box feature, possibly deserving some consideration.
Beta Was this translation helpful? Give feedback.
All reactions