I have a few methods that require a certain condition to be applied to function properly. To avoid code repetition I've created a decorator to check if this condition is applied and only then execute the method. Here is the code:
class ClientHandler:
def __init__(self):
self.__is_dead = False
self.c_ident = c_ident
def __s_operation(func):
@functools.wraps(func)
def check(*args):
self = args[0]
if not self.__is_dead:
func(*args)
else:
logger.error(
"couldn't proceed - client {} is dead!".format(
self.c_ident
)
)
return check
@__s_operation
def __receive_m(self, size) -> bytes:
...
@__s_operation
def close_c(self, message: str) -> None:
...
I was following this answer to be able to use class attributes and call class methods from my decorator, but I ran into 2 errors:
'ClientHandler' object is not callableon thefunc(*args)line, when I'm trying to call a class method from a decorator.function '__s_operation' lacks a positional argument, when I'm trying to add my decorator@__s_operationover a class method.
I don't understand what is the problem and how to solve it, because in the other answer on stack overflow everything seems working. Also, I'm not sure if I will be able to reach my private attributes and private methods from this decorator. I would be grateful for your help. Thank you.