I’ve got a decorator function I’m applying to functions within a class. The decorator is supposed to do a check against an _api member variable. However, I get a global name 'self' is not defined error when I try to do this. What’s the right way?
def requires_api(fn):
def wrapped(*args, **kwargs):
if self._api is not None:
return fn(*args, **kwargs)
else:
return None
return wrapped
@requires_api
def do_something(self):
...
The reference to your instance is in your wrapper function’s
*argsso the nameselfisn’t avaialble. Useargs[0], or just rewrite it as:Naturally, if you do this, your call through to the wrapped function should also include
self.