Skip to content
Related Articles

Related Articles

Python – Pie Syntax (@)
  • Last Updated : 26 Nov, 2020

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  $

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

_________________

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :