Skip to content

Instantly share code, notes, and snippets.

@rfletchr
Last active September 19, 2024 17:44
Show Gist options
  • Save rfletchr/aba85e08d9072c948fb5ded655ab1b56 to your computer and use it in GitHub Desktop.
Save rfletchr/aba85e08d9072c948fb5ded655ab1b56 to your computer and use it in GitHub Desktop.
Generate a weak ref to a python callable accounting for loose functions, bound methods and callable classes.
"""
Generate a weak ref to a python callable accounting for loose functions, bound methods and callable classes.
This allows creating references to python functions without increasing their reference countm and creating
circular dependencies.
"""
import typing
import weakref
import types
def callable_weak_ref(callback: typing.Callable):
if not callable(callback):
raise TypeError("callback must be callable")
elif isinstance(callback, types.FunctionType):
return weakref.ref(callback)
elif isinstance(callback, types.MethodType) and callback.__self__ is not None:
return weakref.WeakMethod(callback)
elif isinstance(callback, types.MethodType) and callback.__self__ is None:
raise TypeError(
"callback must be a bound method, a function, or a callable class"
)
else:
# otherwise it's a callable class.
return weakref.ref(callback)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment