I have some simple decorator that gets an argument:
def deco(name):
def outer(f):
def inner(*args, **kwargs):
print(name)
return f(*args, **kwargs)
return inner
return outer
and a class:
class A:
def __init__(self, name):
self.name = name
@deco(self.name) # This is my goal
def foo(self):
pass
I want to be able to create few instances of A
and each of it will have it’s own version of foo (decorated with deco(name)
).
This obviously doesn’t work as functions are class scope, not instance scope.
I thought about dynamic approach, like:
class A:
def __init__(self, name):
self.name = name
A.foo = deco(name)(A._foo)
def _foo(self):
pass
However it has a problem when we create more instances.
Finally I went for that:
class A:
def __init__(self, name):
self.name = name
self.foo = deco(name)(partial(A._foo, self))
def _foo(self):
pass
Which seems to work, however I have a feeling it’s too hacky. Do I miss something? My real decorator calculates execution time and store it in database and it’s used in many other places like that, so inlining it is not an option.