Exemples concrets

Écrire des fonctions en Python

Shayne Miel

Software Architect @ Duo Security

Chronométrer une fonction

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.
  """
Écrire des fonctions en 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
Écrire des fonctions en Python

Utilisation de 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
Écrire des fonctions en 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
Écrire des fonctions en 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
Écrire des fonctions en Python

Quand utiliser les décorateurs

  • Ajouter un comportement commun à plusieurs fonctions
@timer
def foo():
  # do some computation

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

@timer
def baz():
  # do something else
Écrire des fonctions en Python

Passons à la pratique !

Écrire des fonctions en Python

Preparing Video For Download...