Skip to content

Commit

Permalink
fix: Add descriptive exception when fail to add instance to weakref d…
Browse files Browse the repository at this point in the history
…ictionary (#189)

* add weakref information and test

* more information

* Update src/superqt/utils/_throttler.py

---------

Co-authored-by: Talley Lambert <[email protected]>
  • Loading branch information
Czaki and tlambert03 authored Aug 18, 2023
1 parent 8457563 commit 462eead
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/superqt/utils/_throttler.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,15 @@ def _get_throttler(self, instance, owner, parent, obj):
throttler,
)
except AttributeError:
self._obj_dkt[obj] = throttler
try:
self._obj_dkt[obj] = throttler
except TypeError as e:
raise TypeError(
"To use qthrottled or qdebounced as a method decorator, "
"objects must have `__dict__` or be weak referenceable. "
"Please either add `__weakref__` to `__slots__` or use"
"qthrottled/qdebounced as a function (not a decorator)."
) from e
return throttler

def __get__(self, instance, owner):
Expand Down
35 changes: 35 additions & 0 deletions tests/test_throttler.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,41 @@ def call2():
mock2.assert_called_once()


def test_class_with_slots(qtbot):
class A:
__slots__ = ("count", "__weakref__")

def __init__(self):
self.count = 0

@qdebounced(timeout=4)
def callback(self):
self.count += 1

a = A()
for _ in range(10):
a.callback()

qtbot.wait(5)
assert a.count == 1


@pytest.mark.usefixtures("qapp")
def test_class_with_slots_except():
class A:
__slots__ = ("count",)

def __init__(self):
self.count = 0

@qdebounced(timeout=4)
def callback(self):
self.count += 1

with pytest.raises(TypeError, match="To use qthrottled or qdebounced"):
A().callback()


def test_throttled(qtbot):
mock1 = Mock()
mock2 = Mock()
Expand Down

0 comments on commit 462eead

Please sign in to comment.