Learntofish's Blog

A blog about math, physics and computer science

Posts Tagged ‘Python’

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 »

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 »

Awesome Pycon 2015 presentations

Posted by Ed on April 29, 2015

Watch the Pycon 2015 presentations here. I recommend the excellent talk Facts and Myths about Python names and values by Ned Batchelder. It clears misconceptions you may have regarding assignments, references and values in Python. I love this slide.

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

How to write code the pythonic way

Posted by Ed on April 24, 2015

Check out this interesting article by Constantine Lignos called Anti-Patterns in Python Programming. It demonstrates with several examples how you should write code in Python.

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

Introduction to generators in Python 3.4

Posted by Ed on April 22, 2015

In this blog post I will explain how generators are used in Python 3.4. Read the rest of this entry »

Posted in computer science | Tagged: , , | 1 Comment »

How to write Python code the right way

Posted by Ed on September 18, 2014

Here is a wonderful talk by Raymond Hettinger with the title Transforming Code into Beautiful, Idiomatic Python

Slides can be downloaded here and viewed online here.

His Twitter where he regularly posts short Python code.

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

Visualizing references and objects in Python

Posted by Ed on April 2, 2013

Pythontutor is a website that lets you visualize your Python code.

For instance, type the following Python code into the window:

x = [1, 2, 3]

# reference to the object that x points to
y = x

# create a copy of the list [1,2,3] and store its address at z
z = x[:]

# create a copy of the list [1,2,3] and store its address at z
a = x.copy()

# reference to the object that z points to
a = z

Then, change from Python 2.7 to Python 3.3 in the drop down menu below the window and click the button Visualize Execution.
Click on forward to process the code and observe how the graphics changes on the right.
Pretty neat, isn’t it!

You can also change some settings such as choosing between Python 2.7 and Python 3.3 and using the address id instead of the arrows.
Change the following settings:
inline primitives and nested object -> render all objects on the heap
draw references using arrows -> use text labels for references

Then, paste the following code into the window:

myString = "hello"

# observe how the id changes
myString += " world"
print(myString)

Observe how the id changes if you try to append the string " world" to myString.
That is because strings are immutable in Python such that Python first creates the new string object "hello world".
The addess of this new object is then assigned to the reference myString.

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

Test your Java and Python skills

Posted by Ed on November 8, 2012

CodingBat offers some nice problems to test your programming skills in Java and Python. They are particularly suited for beginners. Some harder problems deal with recursion.

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

Call by Object Reference (Call by Sharing)

Posted by Ed on January 9, 2012

In the following I want to talk about Call by Object Reference also known as Call by Sharing. I will use Python to illustrate the concept.

1. Strange behavior?

Let’s have a look at the following Python code:

def changeList1(x):
    x.append(41)

def changeList2(x):
    x = [41,42]

Save the code in a file callBySharing.py and run it in Read the rest of this entry »

Posted in computer science | Tagged: , , | 1 Comment »