Skip to content

Commit

Permalink
Add support for @property for once_per_instance.
Browse files Browse the repository at this point in the history
  • Loading branch information
aebrahim committed Jan 9, 2024
1 parent b9f0765 commit 9c07982
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
9 changes: 8 additions & 1 deletion once/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

def _is_method(func: collections.abc.Callable):
"""Determine if a function is a method on a class."""
if isinstance(func, (classmethod, staticmethod)):
if isinstance(func, (classmethod, staticmethod, property)):
return True
sig = inspect.signature(func)
return "self" in sig.parameters
Expand Down Expand Up @@ -339,6 +339,11 @@ def once_factory(self) -> _ONCE_FACTORY_TYPE:
def _inspect_function(self, func: collections.abc.Callable):
if isinstance(func, (classmethod, staticmethod)):
raise SyntaxError("Must use @once.once_per_class on classmethod and staticmethod")
if isinstance(func, property):
func = func.fget
self.is_property = True
else:
self.is_property = False
if not _is_method(func):
raise SyntaxError(
"Attempting to use @once.once_per_instance method-only decorator "
Expand All @@ -357,4 +362,6 @@ def __get__(self, obj, cls) -> collections.abc.Callable:
bound_func, self.once_factory(), self.fn_type, self.retry_exceptions
)
self.callables[obj] = callable
if self.is_property:
return callable()
return callable
19 changes: 19 additions & 0 deletions once_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,25 @@ def execute(i):
self.assertEqual(min(results), 1)
self.assertEqual(max(results), math.ceil(_N_WORKERS / 4))

def test_once_per_instance_property(self):
counter = Counter()

class _CallOnceClass:
@once.once_per_instance
@property
def value(self):
nonlocal counter
return counter.get_incremented()

a = _CallOnceClass()
b = _CallOnceClass()
self.assertEqual(a.value, 1)
self.assertEqual(b.value, 2)
self.assertEqual(a.value, 1)
self.assertEqual(b.value, 2)
self.assertEqual(_CallOnceClass().value, 3)
self.assertEqual(_CallOnceClass().value, 4)

def test_once_per_class_classmethod(self):
counter = Counter()

Expand Down

0 comments on commit 9c07982

Please sign in to comment.