Sunday, November 17, 2024
Google search engine
HomeLanguagesPython – Pie Syntax (@)

Python – Pie Syntax (@)

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

defneveropen():

  .

  .

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("$neveropen $")
  
if __name__ == 'main':
    main()


Output:

#—————-#

$neveropen $

#—————-#

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("$neveropen  $")
  
# Driver program to test the code
if __name__ == 'main':
    main()


Output:

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

$neveropen  $

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

_________________

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments