Last active
September 19, 2024 17:44
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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