Python Decorators Demonstration

Posted on Nov 01, 2019


When improving your Python programming language, you must come across the Decorators that are one of the elegant features heavily used in modern libraries and frameworks. To encapsulate a lot of implementation details and leave out a simple interface, the decorators are very good tools to serve the purpose.

Let us take an example of simple login decorator that makes sure the user is logged in before any edition in the posts. This ensures redirecting to the login page by setting the right parameters to redirect back to the same page after successful registration. To avail this function, all you need to do is just put @login_required before the function.

1
2
3
@login_required
def edit_post(post_id):
    ...

Decorators are very easy to use and work with, but writing decorators are even confusing for experienced Python developers. Pop in the article for more explanation on how Python decorators work in simple steps.

Functions #


Functions are also called first-class objects in Python. The functions are values just like numbers, lists, and strings as seen in the following example.

1
2
3
4
5
6
7
>>> def foo():
...     return 1
...
>>>
>>> foo()
1
>>>

Functions also have their own namespace which looks first to find variable names when it encounters them in the function body. To investigate the difference between local and global scope, let's write a simple function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>>
>>> a_string = "This is a global variable"
>>>
>>> def foo():
...     print(locals())
...
>>>
>>> print(globals())
{..., 'a_string': 'This is a global variable'}
>>>
>>> foo() # 2
{}
>>>

Function Scope as a Variable #


In Python scope rule, variable creation always creates a new local variable but accessing the variable looks in the local scope by searching all the enclosing scopes to find a match. This does not mean that we cannot access global variables inside our functions. To modify the function foo to print out global variable we would expect to work as:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>>
>>> a_string = "This is a global variable"
>>>
>>> def foo():
...     print(a_string) #1
...
>>>
>>> foo()
This is a global variable
>>>

Variable Lifetime #


Not only variables live inside a namespace but they also have lifetimes which is important to note. Consider the example to not just scope rules that cause a problem but it also has to do with how function calls and implemented in Python and other languages.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> def foo():
...     x = 1
...
>>> foo()
>>>
>>> print(x) # 1
Traceback (most recent call last):
  ...
NameError: name 'x' is not defined
>>>

Nested functions #


The creation of nested functions is allowed in Python which means we can declare functions inside of the functions and all the scoping and lifetime rules still get applied normally.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>>
>>> def outer():
...     x = 1
...     def inner():
...         print(x) # 1
...     inner() # 2
...
>>> outer()
1
>>>

Decorators #


A closure that takes a function as a parameter and returns a replacement function is called a decorator. Let us look at an example to work with useful decorators.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
>>>
>>> def outer(some_func):
...     def inner():
...         print("before some_func")
...         ret = some_func() # 1
...         return ret + 1
...     return inner
...
>>> def foo():
...     return 1
...
>>> decorated = outer(foo) # 2
>>>
>>> decorated()
before some_func
2
>>>

The decorated variable is a decorated version of foo. In fact, we might want to replace foo with the decorated version altogether without learning any new syntax simply by reassigning the variable that contains our function:

1
2
3
4
5
6
>>>
>>> foo = outer(foo)
>>>
>>> foo # doctest: +ELLIPSIS
<function outer.<locals>.inner at 0x...>
>>>

Now, to trace the function calls we have a beautiful decorator. The decorators can be used to manipulate any programming language using Python language. This has powerful implications so you should now understand how they work and when they are useful.

Author Bio

Kibo Hutchinson is a Technology analyst at Tatvasoft UK which is a software development company in London. She strongly believes that knowledge is meant to be shared and in this post she is sharing her insights on Python.


Other Tutorials (Sponsors)