Binding API that uses direct references to objects #3080
Replies: 2 comments 1 reply
-
I don't have much to add other than to say I have had the same thought. |
Beta Was this translation helpful? Give feedback.
-
Great idea, @kj4tmp! That's exactly what we had in mind when designing NiceGUI's binding API around three years ago. We thought it would feel much nicer than fiddling with strings. And we actually implemented it as a separate library https://github.com/zauberzeug/binding/ and integrated it in NiceGUI 0.2.0: 3915a3d. But as described in https://github.com/zauberzeug/binding?tab=readme-ov-file#implementation-and-dependencies, there were several tricks required to get this working. Especially relying on the inspect and executing packages to detect object and attribute name felt a little unstable. When a binding function receives a "source" or "target", it usually only sees the value (e.g. def _get_parent_and_argument(method_name, nesting):
sep = f'.{method_name}('
expression = inspect.stack()[2].code_context[0].strip().split(sep)[0]
callFrame = inspect.currentframe().f_back.f_back
self_obj, self_name = _extract_object(expression, callFrame)
for _ in range(nesting):
callFrame = callFrame.f_back
callNode = Source.executing(callFrame).node
source = Source.for_frame(callFrame)
expression = source.asttokens().get_text(callNode.args[0])
other_obj, other_name = _extract_object(expression, callFrame)
return self_obj, self_name, other_obj, other_name This allows to write: label.text.bind_from(input.value) But it breaks as soon as the user deviates from the intended usage, e.g. when writing: first_name = input.value
label.text.bind_from(first_name) And another problem with this fancy API was that Long story short, this API felt very compelling, but required nasty hacks to ultimately work. |
Beta Was this translation helpful? Give feedback.
-
Currently, the binding API requires providing an object and a string. One footgun with this approach is that it is very easy to have a typo in the string.
Could we perhaps have an API that takes a direct reference to the object to bind to?
The existing api:
The api could be significantly easier to use if the following was possible:
Of course the developer would need to be careful to preserve this reference (which we already have to do since there are already existing footguns related to overwriting these references to existing objects and breaking the binding connection).
Beta Was this translation helpful? Give feedback.
All reactions