Learn how to create and use Python Decorators

Post to Twitter

Python is an amazing language to program in. Its easy to get started and you can dig as deep as you want. Today I’m going to show you how to use Python Decorators.

Let’s say you were organizing a party and wanted to put a list together of friends. Lets also assume that anyone named “Joe” should be removed from the list (not meaning to pick on anyone named Joe but I need a name for the example). We could write a program to populate the list and then iterate through the list and remove anyone with the name Joe, however, in this case I’ll use a decorator. Although this is a trivial example it will demonstrate how to use decorators very easily.

Create a new Python file called app.py add the following code to it:

if __name__ == "__main__":
    party_invites = []
    party_invites.append("Jessica")
    party_invites.append("Tom")
    party_invites.append("Bob")
    party_invites.append("Joe")
    
    print(party_invites)

If you run the program you will see the following output:

['Jessica', 'Tom', 'Bob', 'Joe']

Obviously we could just search and remove Joe from the list. However, let’s use a decorator to do this for us.

def nojoes(func):
    def drop_joe(party_attendees):
        func([attendee for attendee in party_attendees if attendee != 'Joe'])
    return drop_joe


@nojoes
def party(party_attendees):
    print(party_attendees)


if __name__ == "__main__":
    party_invites = []
    party_invites.append("Jessica")
    party_invites.append("Tom")
    party_invites.append("Bob")
    party_invites.append("Joe")

    party(party_invites)

As you can see I added a function called party that takes a list of potential party attendees and then prints out the list. However, you probably noticed the decorator called @nojoes. The nojoes function has a closure inside of it which uses a list comprehension and then removes any Joes from the list and then calls back into the decorated function with the modified list.

The results look like this when you run it:

['Jessica', 'Tom', 'Bob']

Typically you will see decorators used in REST/Web frameworks like Falcon, Flask, or Bottle. In those cases they make extensive use of decorators for routes. You will also see decorators used in projects like Celery marking functions as tasks.

Post to Twitter

This entry was posted in Open Source, Python. Bookmark the permalink.