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
def decor(func):
print ( "#----------------#" )
func()
print ( "#----------------#" )
@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
def decor1(func):
print ( "_________________" )
def decor2(func):
print ( "$****************$" )
func()
print ( "$****************$" )
@decor1
@decor2
def main():
print ( "$ GeeksforGeeks $" )
if __name__ = = 'main' :
main()
|
Output:
$****************$
$ GeeksforGeeks $
$****************$
_________________
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...