Real-world examples

Writing Functions in Python

Shayne Miel

Software Architect @ Duo Security

Time a function

import time

def timer(func):
  """A decorator that prints how long a function took to run.

  Args:
    func (callable): The function being decorated.

  Returns:
    callable: The decorated function.
  """
Writing Functions in Python
import time

def timer(func):
  """A decorator that prints how long a function took to run."""

# Define the wrapper function to return. def wrapper(*args, **kwargs):
# When wrapper() is called, get the current time. t_start = time.time()
# Call the decorated function and store the result. result = func(*args, **kwargs)
# Get the total time it took to run, and print it. t_total = time.time() - t_start print('{} took {}s'.format(func.__name__, t_total))
return result
return wrapper
Writing Functions in Python

Using timer()

@timer
def sleep_n_seconds(n):
  time.sleep(n)
sleep_n_seconds(5)
sleep_n_seconds took 5.0050950050354s
sleep_n_seconds(10)
sleep_n_seconds took 10.010067701339722s
Writing Functions in Python
def memoize(func):
  """Store the results of the decorated function for fast lookup
  """

# Store results in a dict that maps arguments to results cache = {}
# Define the wrapper function to return. def wrapper(*args, **kwargs): # Define a hashable key for 'kwargs'. kwargs_key = tuple(sorted(kwargs.items()))
# If these arguments haven't been seen before, if (args, kwargs_key) not in cache:
# Call func() and store the result. cache[(args, kwargs_key)] = func(*args, **kwargs)
return cache[(args, kwargs_key)]
return wrapper
Writing Functions in Python
@memoize
def slow_function(a, b):
  print('Sleeping...')
  time.sleep(5)
  return a + b
slow_function(3, 4)
Sleeping...

7
slow_function(3, 4)
7
Writing Functions in Python

When to use decorators

  • Add common behavior to multiple functions
@timer
def foo():
  # do some computation

@timer
def bar():
  # do some other computation

@timer
def baz():
  # do something else
Writing Functions in Python

Let's practice!

Writing Functions in Python

Preparing Video For Download...