Open In App

Python – Pie Syntax (@)

Last Updated : 26 Nov, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

A decorator, is a callable that is used to extend the functionality of other callables. In simple words, It allows you to “decorate” a function with another function. The “@” symbol in this context is sometimes referred to as Pie Syntax to a decorator. The pie syntax makes it more easy to access and extend. 

Since, we already had decoration with staticmethod() and classmethod(). So, a function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators can be applied in nested fashion.

Syntax:

(Pie_syntax) <decorator_name>
any_callable

Example:

@gfg

def geeks():

  .

  .

For cases where repetitive assignments and calling statements seem useless, then pie syntax is a life savior. We can just name the decorating function after the @ symbol, and put this before the function to decorate.

Following programs will help you understand this better:

Program 1:

Python3




# defining the decorator
def decor(func):
    print("#----------------#")
    func()
    print("#----------------#")
  
# using the decorator
@decor
def main():
    print("$ GeeksforGeeks $")
  
if __name__ == 'main':
    main()


Output:

#—————-#

$ GeeksforGeeks $

#—————-#

Chaining pie syntax

We can also have multiple decorators in a function, not necessarily only one. But, keeping in mind the order of the decorators is important. The order in which the decorators will be called, will directly affect the output.

Program 2:

Python3




# defining the 1st decorator
def decor1(func):
    print("_________________")
  
# defining the 2nd decorator
def decor2(func):
    print("$****************$")
    func()
    print("$****************$")
  
# using the decorator
@decor1
@decor2
def main():
    print("$ GeeksforGeeks  $")
  
# Driver program to test the code
if __name__ == 'main':
    main()


Output:

$****************$

$ GeeksforGeeks  $

$****************$

_________________



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads