Rigel Di Scala

1. Intro.

Decorators are a useful addition to the Python programming language, but can be difficult to grasp at first. If you already read some articles on Python decorators and found them hard to understand, this tutorial, aimed at beginners, will attempt at explaining how you can use them in a simple and, hopefully, comprehensible way.

2. So what are decorators?

Put simply, “decorating” a function means embedding it inside another “decorator” function or class.

If you had a previous exposure to Django, the popular Web application framework written in Python, you’ll probably have encountered the ‘@require_login decorator’. Its purpose is quite simple: any ‘view’ method decorated with it will be accessible only to authenticated users.

@require_login def my_index_page(): html = "<p>Welcome to my boring webpage, user!</p>" return html

Basically, this code means: “the user will be required to login before he or she can access the page content.”

In this tutorial, we will be writing a very similiar decorator function.

3. Our first decorator.

If you ever used Windows 7 or Vista you probably encountered a security mechanism called ‘UAC’. It attempts to protect the operating system from malware by requiring the user to explicitly ‘accept’ or ‘deny’ the execution of any program that requires

super-user privileges.

“Windows needs your permission to continue. Continue or Cancel?”.

We will replicate this functionality with a decorator function called ”authorize”, that will require the user to confirm the execution of any function decorated with it.

4. Let’s code it!

First of all, let’s define a very simple function:

def say_hello(): print "Hello world!"

The say_hello() command should be fairly self explanatory!

We will now port the UAC mechanism to Python, call it ‘authorize()’, and decorate our function with it. Let’s fire up the Python interpreter and enter the following code:

>>> def authorize(command): >>> if raw_input('>>> Do you wish to execute this command? ') == "y": >>> return command()

It’s a very simple function: a command will be passed to our decorator function as a value and a confirmation input will be requested from the user; if the user enters the letter ‘y’ as a confirmation, the command will be executed.

Let’s decorate our say_hello() function and see if it works…

>>> @authorize >>> def say_hello(): >>> print "Hello world!"

The output will be:

[Do you wish to execute this command?] y

Hello world!

Congratulations! You’ve just written your first decorator. Take a moment to let this sink in… then start reading the next chapter.

Pages: 1 2 3