Home > Blockchain >  What is the use of '@f' in python?
What is the use of '@f' in python?

Time:01-25

#the code given is:

def f(a):
    print('hello')

@f    

def f(a,b):
    return a%b

f(4,0)    

What I expected to happen was a zero division error, instead it printed hello. When I write the same code without '@f' it gives the expected result as output I've never seen symbol/expression being used in python This is new and Google too has nothing about it

CodePudding user response:

Decorator syntax is a shorthand for a particular function application.

@f
def f(a, b):
    return a%b

is roughly equivalent to

def tmp(a, b):
    return a % b

tmp2 = f(tmp)

f = tmp2

(Reusing the name f for everything makes this tricker to understand.)

First, your division-by-zero function is defined. Next, your original function f is called: it prints hello and returns None. Finally, you attempt to call None with two arguments, but it isn't callable, resulting in the TypeError you allude to.

In short, the decorator syntax takes care of treating all the things that would otherwise have been named f as distinct objects and applying things in the correct order.

CodePudding user response:

In Python, the "@" symbol is used to denote a decorator, which is a way to modify or extend a function or class. In this specific example, the function "f" is being used as a decorator for the function "f(a, b)". However, since it's not being used correctly and the decorator function is not returning anything the code will raise a TypeError: 'NoneType' object is not callable. If you want to use the decorator function you should define it correctly like this

def f(decorated_func):
    def wrapper(*args, **kwargs):
        print('hello')
        return decorated_func(*args, **kwargs)
    return wrapper

and then use the decorator on the function you want to decorate like this

@f
def f(a,b):
  return a%b

and then call the function f(4,0)

  • Related