Python Decorators

Before reading this article, I would recommend to go through the below articles.

  • A decorator is a function that accepts another function as an argument.
  • The decorator generally modify or update the function it accepted and return the modified function.
  • Decorator starts with @ symbol followed by the name of the function and need to keep this decorator one line before the function definition.
>>> def outer(funobj):
...     def inner(table, max):
...             print("Inner")
...             funobj(table, max)
...     return inner
...
>>> @outer
... def mul(table, n):
...     for x in range(1, n+1):
...             print(f" {table} x {x} = {x * table}")
...
>>> mul(10,10)
Inner
 10 x 1 = 10
 10 x 2 = 20
 10 x 3 = 30
 10 x 4 = 40
 10 x 5 = 50
 10 x 6 = 60
 10 x 7 = 70
 10 x 8 = 80
 10 x 9 = 90
 10 x 10 = 100
-----------------------------------------------------------
>>> def outer(fun):
...     def inner(n):
...             mylist = []
...             for x in range(0,n+1):
...                     mylist.append(x)
...             result = mylist
...             return result
...     return inner
...
>>> @outer
... def PrintNumber(n):
...     return n
...
>>> PrintNumber(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> PrintNumber(5)
[0, 1, 2, 3, 4, 5]
-----------------------------------------------------------

>>> def outer(fun):
...     def inner(name):
...             upper = fun(name).upper()
...             lower = fun(name).lower()
...             return upper, lower
...     return inner
...
>>> @outer
... def upperlower(name):
...     return name
...
>>> upperlower("Girish")
('GIRISH', 'girish')

-----------------------------------------------------------

>>> def outer(fun):
...     def inner(mylist):
...             total = sum(mylist)
...             return total
...     return inner
...
>>> @outer
... def SUM(myList):
...     return myList
...
>>> SUM([1,2,3,4,5,6,7,8,9])
45
-----------------------------------------------------------

>>> def outer(fun):
...     def inner(mylist):
...             minimum = min(mylist)
...             maximum = max(mylist)
...             total = sum(mylist)
...             return minimum, maximum, total
...     return inner
...
>>> @outer
... def MinMaxTotal(mylist):
...     return myList
...
>>> MinMaxTotal([5,8,10])
(5, 10, 23)

References

  • https://www.python.org/dev/peps/pep-0318/
  • https://docs.python.org/3/reference/compound_stmts.html

Learn more about python features in our upcoming blog articles.

Happy Learning!