Python - Decorators
Solution 1:
Your decorator should look like this:
defwrapper(func):
definner(x, y): # inner function needs parametersifissubclass(type(x), int): # maybe you looked for isinstance?return func(x, y) # call the wrapped functionelse:
return'invalid values'return inner # return the inner function (don't call it)
Some points to note:
issubclass
expects a class as first argument (you could replace it with a simple try/except TypeError).- the wrapper should return a function, not the result of a called function
- you should actually call the wrapped function in the inner function
- your inner function didn't have parameters
You can find a good explanation of decorators here.
Solution 2:
There are three issues I see with your current code.
First, you're calling the inner
function, rather than returning a reference to it.
Second, your inner
function doesn't take the same arguments as the function you're decorating. In this case, you need to take at least the x
argument explicitly (some inner functions can use *args
and **kwargs
exclusively, but aparently not yours).
Lastly, you're never calling the wrapped function. While this isn't strictly required (it might be useful to swap out a method with a decorator during development), usually you want to call the function at some point during the inner function's code.
So, to wrap the whole thing together, I think you want your code to be something like this:
defwrapper(func):
definner(x, y):
ifissubclass(x, int): # issue 2return func(x, y) # issue 3else:
return"invalid values"# consider raising an exception here instead!return inner # issue 1
Solution 3:
You may also raise an exception if you would like to terminate the add method properly if type check fails. like this
defcheck_int_types(func):
deftype_checker(x, y):
ifissubclass(type(x), int) andissubclass(type(y), int):
return func(x, y)
raise Exception("Invalid types: {}, {}".format(x, y))
return type_checker
@check_int_typesdefadd(a, b):
return a + b
defmain():
x = y = 15.0print add(x, y)
if __name__ == '__main__':
main()
Result:
Traceback (most recent call last):
File "deco_test.py", line 17, in <module>
main()
File "deco_test.py", line 14, in main
print add(x, y)
File "deco_test.py", line 5, in type_checker
raise Exception("Invalid types: {}, {}".format(x, y))
Exception: Invalid types: 15.0, 15.0
Solution 4:
this might work.
defwrapper(func):
definner(*args,**kwargs):
if ((args[0] isint) and (args[1] isint)): passelse: return'invalid values'return inner
@wrapperdefadd(x,y):
return x+y
print add('a',2)
Solution 5:
What about this .
def wrapper(func):
def inner():
if isinstance(func,int):
return func(x, y)
else: return'invalid values'returninner()
Post a Comment for "Python - Decorators"