python-coder python-coder - 1 month ago 5
Python Question

Python - Decorators

I'm trying to learn Decorators .
I understood the concept of it and now trying to implement it.

Here is the code that I've written
The code is self-explanatory. It just checks whether the argument passed in

int
or not.

def wrapper(func):
def inner():
if issubclass(x,int): pass
else: return 'invalid values'

return inner()

@wrapper
def add(x,y):
return x+y

print add('a',2)


It's throwing error saying
global name 'x' is not defined
. I understand that it is not defined under
inner
, but didnt know how to rectify this code? Where I'm going wrong?

Answer

Your decorator should look like:

def wrapper(func):
    def inner(x, y): # inner function needs parameters
        if issubclass(type(x), int): # maybe you looked for isinstance?
            return func(x, y) # call the wrapped function
        else: 
            return 'invalid values'
    return inner # return the inner function (don't call it)

Some points:

  • 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 had parameters

You can find a good explanation of decorators here.