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

Add an option to make the effect of sync_attr and sync_attrs permanent #168

Merged
merged 1 commit into from
Mar 16, 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
92 changes: 62 additions & 30 deletions src/asynckivy/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,20 +147,29 @@ def __exit__(self, *args):

class sync_attr:
'''
Returns a context manager that creates one-directional binding between attributes.
Creates one-directional binding between attributes.

.. code-block::

import types

widget = Widget()
widget = Widget(x=100)
obj = types.SimpleNamespace()

with sync_attr(from_=(widget, 'x'), to_=(obj, 'xx')):
widget.x = 10
assert obj.xx == 10 # synchronized
obj.xx = 20
assert widget.x == 10 # but not the other way around
sync_attr(from_=(widget, 'x'), to_=(obj, 'xx')):
assert obj.xx == 100 # synchronized
widget.x = 10
assert obj.xx == 10 # synchronized
obj.xx = 20
assert widget.x == 10 # but not the other way around

To make its effect temporary, use it with a with-statement:

.. code-block::

# The effect lasts only within the with-block.
with sync_attr(...):
...

This can be particularly useful when combined with :func:`transform`.

Expand All @@ -169,7 +178,7 @@ class sync_attr:
from kivy.graphics import Rotate

async def rotate_widget(widget, *, angle=360.):
rotate = Rotate(origin=widget.center)
rotate = Rotate()
with (
transform(widget) as ig,
sync_attr(from_=(widget, 'center'), to_=(rotate, 'origin')),
Expand All @@ -178,23 +187,35 @@ async def rotate_widget(widget, *, angle=360.):
await anim_attrs(rotate, angle=angle)

.. versionadded:: 0.6.1

.. versionchanged:: 0.8.0
The context manager now applies its effect upon creation, rather than when its ``__enter__()`` method is
called, and ``__enter__()`` no longer performs any action.

Additionally, the context manager now assigns the ``from_`` value to the ``to_`` upon creation:

.. code-block::

with sync_attr((widget, 'x'), (obj, 'xx')):
assert widget.x == obj.xx
'''
__slots__ = ('_from', '_to', '_bind_uid', )
__slots__ = ("__exit__", )

def __init__(self, from_: T.Tuple[EventDispatcher, str], to_: T.Tuple[T.Any, str]):
self._from = from_
self._to = to_
def __init__(self, from_: tuple[EventDispatcher, str], to_: tuple[T.Any, str]):
setattr(*to_, getattr(*from_))
bind_uid = from_[0].fbind(from_[1], partial(self._sync, setattr, *to_))
self.__exit__ = partial(self._unbind, *from_, bind_uid)

@staticmethod
def _sync(setattr, obj, attr_name, event_dispatcher, new_value):
setattr(obj, attr_name, new_value)

def __enter__(self, partial=partial, sync=partial(_sync, setattr)):
self._bind_uid = self._from[0].fbind(self._from[1], partial(sync, *self._to))
@staticmethod
def _unbind(event_dispatcher, event_name, bind_uid, *__):
event_dispatcher.unbind_uid(event_name, bind_uid)

def __exit__(self, *args):
self._from[0].unbind_uid(self._from[1], self._bind_uid)

del _sync
def __enter__(self):
pass


class sync_attrs:
Expand All @@ -221,8 +242,8 @@ class sync_attrs:
from kivy.graphics import Rotate, Scale

async def scale_and_rotate_widget(widget, *, scale=2.0, angle=360.):
rotate = Rotate(origin=widget.center)
scale = Scale(origin=widget.center)
rotate = Rotate()
scale = Scale()
with (
transform(widget) as ig,
sync_attrs((widget, 'center'), (rotate, 'origin'), (scale, 'origin')),
Expand All @@ -235,21 +256,32 @@ async def scale_and_rotate_widget(widget, *, scale=2.0, angle=360.):
)

.. versionadded:: 0.6.1

.. versionchanged:: 0.8.0
The context manager now applies its effect upon creation, rather than when its ``__enter__()`` method is
called, and ``__enter__()`` no longer performs any action.

Additionally, the context manager now assigns the ``from_`` value to the ``to_`` upon creation:

.. code-block::

with sync_attrs((widget, 'x'), (obj, 'xx')):
assert widget.x is obj.xx
'''
__slots__ = ('_from', '_to', '_bind_uid', )
__slots__ = ("__exit__", )

def __init__(self, from_: T.Tuple[EventDispatcher, str], *to_):
self._from = from_
self._to = to_
def __init__(self, from_: tuple[EventDispatcher, str], *to_):
sync = partial(self._sync, setattr, to_)
sync(None, getattr(*from_))
bind_uid = from_[0].fbind(from_[1], sync)
self.__exit__ = partial(self._unbind, *from_, bind_uid)

@staticmethod
def _sync(setattr, to_, event_dispatcher, new_value):
for obj, attr_name in to_:
setattr(obj, attr_name, new_value)

def __enter__(self, partial=partial, sync=partial(_sync, setattr)):
self._bind_uid = self._from[0].fbind(self._from[1], partial(sync, self._to))

def __exit__(self, *args):
self._from[0].unbind_uid(self._from[1], self._bind_uid)
_unbind = staticmethod(sync_attr._unbind)

del _sync
def __enter__(self):
pass
5 changes: 4 additions & 1 deletion tests/test_utils_sync_attr.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def human_cls():
from kivy.properties import NumericProperty

class Human(EventDispatcher):
age = NumericProperty()
age = NumericProperty(10)

return Human

Expand All @@ -23,6 +23,7 @@ def test_sync_attr(human):

obj = types.SimpleNamespace()
with ak.sync_attr(from_=(human, 'age'), to_=(obj, 'AGE')):
assert obj.AGE == 10
human.age = 2
assert obj.AGE == 2
human.age = 0
Expand All @@ -37,6 +38,8 @@ def test_sync_attrs(human):

obj = types.SimpleNamespace()
with ak.sync_attrs((human, 'age'), (obj, 'AGE'), (obj, 'age')):
assert obj.AGE == 10
assert obj.age == 10
human.age = 2
assert obj.AGE == 2
assert obj.age == 2
Expand Down