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

Copyable classes with bindable properties #4251

Merged
merged 3 commits into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions nicegui/binding.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import asyncio
import copyreg
import dataclasses
import time
import weakref
Expand Down Expand Up @@ -36,7 +37,8 @@
bindable_properties: Dict[Tuple[int, str], weakref.finalize] = {}
active_links: List[Tuple[Any, str, Any, str, Callable[[Any], Any]]] = []

T = TypeVar('T', bound=type)
TC = TypeVar('TC', bound=type)
T = TypeVar('T')


def _has_attribute(obj: Union[object, Mapping], name: str) -> Any:
Expand Down Expand Up @@ -170,6 +172,8 @@ def __get__(self, owner: Any, _=None) -> Any:

def __set__(self, owner: Any, value: Any) -> None:
has_attr = hasattr(owner, '___' + self.name)
if not has_attr:
_make_copyable(type(owner))
value_changed = has_attr and getattr(owner, '___' + self.name) != value
if has_attr and not value_changed:
return
Expand Down Expand Up @@ -217,7 +221,7 @@ def reset() -> None:


@dataclass_transform()
def bindable_dataclass(cls: Optional[T] = None, /, *,
def bindable_dataclass(cls: Optional[TC] = None, /, *,
bindable_fields: Optional[Iterable[str]] = None,
**kwargs: Any) -> Union[Type[DataclassInstance], IdentityFunction]:
"""A decorator that transforms a class into a dataclass with bindable fields.
Expand Down Expand Up @@ -255,3 +259,23 @@ def wrap(cls_):
bindable_property.__set_name__(dataclass, field_name)
setattr(dataclass, field_name, bindable_property)
return dataclass


def _make_copyable(cls: Type[T]) -> None:
"""Tell the copy module to update the ``bindable_properties`` dictionary when an object is copied."""
if cls in copyreg.dispatch_table:
return

def _pickle_function(obj: T) -> Tuple[Callable[..., T], Tuple[Any, ...]]:
reduced = obj.__reduce__()
assert isinstance(reduced, tuple)
creator = reduced[0]

def creator_with_hook(*args, **kwargs) -> T:
copy = creator(*args, **kwargs)
for attr_name in dir(obj):
if (id(obj), attr_name) in bindable_properties:
bindable_properties[(id(copy), attr_name)] = copy
return copy
return (creator_with_hook, *reduced[1:])
copyreg.pickle(cls, _pickle_function)
28 changes: 27 additions & 1 deletion tests/test_binding.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import copy
import weakref
from typing import Dict, Optional, Tuple

from selenium.webdriver.common.keys import Keys

from nicegui import binding, ui
from nicegui.testing import Screen
from nicegui.testing import Screen, User


def test_ui_select_with_tuple_as_key(screen: Screen):
Expand Down Expand Up @@ -128,6 +129,31 @@ class TestClass:
assert binding.active_links[0][1] == 'not_bindable'


async def test_copy_instance_with_bindable_property(user: User):
@binding.bindable_dataclass
class Number:
value: int = 1

x = Number()
y = copy.copy(x)

ui.label().bind_text_from(x, 'value', lambda v: f'x={v}')
assert len(binding.bindings) == 1
assert len(binding.active_links) == 0

ui.label().bind_text_from(y, 'value', lambda v: f'y={v}')
assert len(binding.bindings) == 2
assert len(binding.active_links) == 0

await user.open('/')
await user.should_see('x=1')
await user.should_see('y=1')

y.value = 2
await user.should_see('x=1')
await user.should_see('y=2')


def test_automatic_cleanup(screen: Screen):
class Model:
value = binding.BindableProperty()
Expand Down