I have a class, and I would prefer that people call a factory method in order to create instance of the class instead of instantiating the class directly.
One of a few different reasons to use a factory method is so that we can use functools.wrap
to wrap un-decorated callable.
import inspect
class Decorator:
def __init__(self, kallable):
self._kallable = kallable
@classmethod
def make_decorator(kls, kallable):
wrapped_kallable = kls(kallable)
return functools.wrap(wrapped_kallable, kallable)
def __call__(self, *args, **kwargs):
func_name = self._kallable.__name__
func_name = inspect.currentframe().f_code.co_name
print("ENTERING FUNCTION ", func_name)
ret_val = self._kallable(*args, **kwargs)
print("LEAVING FUNCTION", self._kallable)
return ret_val
Printing "ENTERING FUNCTION "
is kind of a silly thing to do, I wanted to show you a minimal reproducible example of what I am trying to do (create a decorator-class which uses functools.wrap
and which is instantiated from a factory method)