Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 532
python-coder Avatar asked Jan 06 '14 07:01

python-coder


People also ask

What do Python decorators do?

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate.

When should I use Python decorators?

You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.

What are the types of decorators in Python?

In fact, there are two types of decorators in Python — class decorators and function decorators — but I will focus on function decorators here.

What is the Python decorator give an example?

Example:2 - @staticmethod decorator- The @staticmethod is used to define a static method in the class. It is called by using the class name as well as instance of the class.


1 Answers

Your decorator should look like this:

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 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.

like image 69
sloth Avatar answered Oct 11 '22 04:10

sloth