Learntofish's Blog

A blog about math, physics and computer science

Python decorators

Posted by Ed on April 5, 2018

In short, a Python decorator is a function that takes another function and adds some functionality to it.

Example

Let’s consider the following function:

def greet(my_name):
    print("Hello {}!".format(my_name))

greet("Alice")

The output is simply

Hello Alice!

Suppose we wanted to add some functionality to our function and additionally print “Today is a wonderful day.” without changing the function itself. We can do this with a so-called decorator as follows:

def my_decorator(func):

  # create decorated function
  def decorated_func(*args, **kwargs):
    func(*args, **kwargs)
    print("Today is a wonderful day.")
  
  # return decorated function
  return decorated_func
  
#-----------------------------

def greet(my_name):
  print("Hello {}!".format(my_name))

#-----------------------------

decorated_greet = my_decorator(greet)
decorated_greet("Alice")

The output then becomes

Hello Alice!
Today is a wonderful day.

We could also reassign the name “greet” to the decorated function:

def my_decorator(func):

  # create decorated function
  def decorated_func(*args, **kwargs):
    func(*args, **kwargs)
    print("Today is a wonderful day.")
  
  # return decorated function
  return decorated_func
  
#-----------------------------

def greet(my_name):
  print("Hello {}!".format(my_name))

#-----------------------------

# reassign function name 'greet'
greet = my_decorator(greet)
greet("Alice")

Whenever we call greet(“Alice”) the output from now on will be

Hello Alice!
Today is a wonderful day.

This means we have changed the functionality of “greet” without changing the code for the function definition of “greet”! In Python we have a special syntax. Instead of writing

greet = my_decorator(greet)

we can simply add our decorator “my_decorator” above the function definition of “greet”:

def my_decorator(func):

  # create decorated function
  def decorated_func(*args, **kwargs):
    func(*args, **kwargs)
    print("Today is a wonderful day.")
  
  # return decorated function
  return decorated_func
  
#-----------------------------

# decorator syntax in Python

@my_decorator
def greet(my_name):
  print("Hello {}!".format(my_name))

#-----------------------------

greet("Alice")

References

Here are some good references to understand decorators in Python:

Python Tutorial: Decorators – Dynamically Alter The Functionality Of Your Functions
is a Youtube video by Corey Schafer. I also recommend watching his two other videos on First class functions and Closures.

Python Decorators Tutorial
on the Youtube channel codebasics.

A guide to Python’s function decorators
by Ayman Farhat on his blog The Code Ship.

Advertisements

Posted in programming | Tagged: , | Leave a Comment »

Air Force to software engineer – an inspiring story

Posted by Ed on March 28, 2018

Read this story by Jordan D. Jackson, an Air Force vet, that became a sofware engineer. Despite not having any coding experience his persistence landed him a job at twitter.

He used websites such as FreeCodeCamp, CodeAcademy, TheOdinProject, CodeSchool and Hackerrank to teach himself programming. He also began networking and met the right people at the right time.

Posted in Education, Uncategorized | Leave a Comment »

Probability and statistics videos

Posted by Ed on October 15, 2017

Here are some good videos on probability and statistics. I also found them perfect as a quick refresher.

Probability Course by Hossein Pishro-Nik
Video and online book

ActuarialPath
Videos

And here a full university course:

Probabilistic Systems Analysis and Applied Probability
Videos and assignments

Posted in mathematics | Tagged: , | Leave a Comment »

Things flying in compressed air

Posted by Ed on November 12, 2016

Posted in physics | Leave a Comment »

Lectures on C++ STL

Posted by Ed on April 25, 2016

Check out these Channel 9 lectures by Stephan T. Lavavej on the Standard Template Library (STL) in C++.

From the website’s description:

Learn all about the Standard Template Library (STL)  from the great Stephan T. Lavavej (STL), Microsoft’s keeper of the STL cloth (this means he manages the partnership with the owners of STL and Microsoft, including, of course, bug fixes and enhancements to the STL that ships as part of Visual C++).

Posted in programming | Tagged: , | 1 Comment »

Python 3: Inheritance and super()

Posted by Ed on April 23, 2016

Inheritance in Object Oriented Programming (OOP) means that you create a new class by extending an existing class. For example, suppose we have a class Shape with the attribute position. Then we can create a new class Circle by taking Shape and extending it by a new attribute center: Read the rest of this entry »

Posted in computer science, programming | Tagged: , , | Leave a Comment »

Learn to code with these websites

Posted by Ed on April 7, 2016

Two websites that teach you how to code are codeschool and codeacademy. They come with videos followed by interactive questions.

You can find more recommendations at:
Hongiat
Reddit
Gizmodo

Posted in programming, Uncategorized | Tagged: , | Leave a Comment »

How Patreon was founded

Posted by Ed on April 7, 2016

You’ve probably heard of Patreon, a crowdfunding platform that allows people to support artists and creators via a subscription where only 5% are kept by Patreon as commission.

Listen to Jack Conte explaining how he founded Patreon together with Sam Yam. I admire the company because the idea is simple and yet so ingenious.  Conte and Yam were smart enough to recognize a niche and quickly  realise their idea.

Posted in music, Uncategorized | Tagged: , , | Leave a Comment »

Playing Flappy Bird within Super Mario World

Posted by Ed on April 3, 2016

Check out this pretty impressive video by Sethbling showing how to inject the source code for Flappy Bird into Super Mario World. The programming is done within the game of Super Mario World.

Posted in games, programming, Uncategorized | Tagged: , , | Leave a Comment »

Try Linux with these simple steps

Posted by Ed on March 26, 2016

Have you ever wanted to try Linux? Here is how you can do it, and all you need is a USB memory stick. Read the rest of this entry »

Posted in computer science, Education | Tagged: , , , | Leave a Comment »