0

#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

chepner
  • 497,756
  • 71
  • 530
  • 681
Mrunal
  • 11
  • 2

1 Answers1

4

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.

chepner
  • 497,756
  • 71
  • 530
  • 681