Search code examples
pythonweak-referencescommand-pattern

Python WeakRef.WeakMethod pass arguments


Currently I'm trying to create a class using the Command Pattern. For the action class, I have something similar to this:

class SimpleCommand(Command):
    """
    Some commands can implement simple operations on their own.
    """
    def __init__(self, callable: Callable) -> None:
        self._callable = callable

    def execute(self) -> None:
        self._callable()

To prevent memory leaks, I plan to maintain a weak reference to the callable method. Is there any way I can use weakref.WeakMethod and pass multiple arguments? I've attempted to use functools.partial, but this causes the the weak method to be perceived as dead.


Solution

  • I ended up adding some additional arguments to the SimpleCommand class to allow arguments to be passed to the WeakMethod.

    class SimpleCommand(Command):
    """
    Some commands can implement simple operations on their own.
    """
    def __init__(self, callable: Callable, *callable_args, **callable_kwargs) -> None:
        self._callable = weakref.WeakMethod(callable)
        self._callable_args = callable_args
        self._callable_kwargs = callable_kwargs
    
    def execute(self) -> None:
        if self._callable() is not None:
            self._callable()(*self._callable_args, **self._callable_kwargs)