Reputation: 1053
I have a python class, Something
. I would like to create a method, borrowed
, which would check for whether the instance variable blue
of Something
is None
.
How would I create @check_none
on the instance method so that it would check for an instance variable? Using self
in the decorator function did not work ;(
Example:
def check_token(func):
def inner(*args, **kwargs):
if self.token == None:
raise ValueError
else:
return func(*args, **kwargs)
return inner
class Something(object):
def __init__(self, token=None):
self.token = token
@check_token
def testfunction(self):
print "Test"
Yields a global name 'self' is not defined
error.
Upvotes: 0
Views: 1575
Reputation: 1123420
Your inner function doesn't have a self
argument; add it in and pass it on:
def check_token(func):
def inner(self, *args, **kwargs):
if self.token is None:
raise ValueError
else:
return func(self, *args, **kwargs)
return inner
The inner
function replaces the original method when decorated and is passed in the same self
argument.
Alternatively, you can use args[0].token
, since self
is simply the first positional argument.
Note that I replaced your == None
test with the recommended is None
test.
Demo:
>>> def check_token(func):
... def inner(self, *args, **kwargs):
... if self.token is None:
... raise ValueError
... else:
... return func(self, *args, **kwargs)
... return inner
...
>>> class Something(object):
... def __init__(self, token=None):
... self.token = token
... @check_token
... def testfunction(self):
... print "Test"
...
>>> Something().testfunction()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in inner
ValueError
>>> Something('token').testfunction()
Test
Upvotes: 4