Voorbeelden uit de praktijk

Functies schrijven in Python

Shayne Miel

Software Architect @ Duo Security

Meet de tijd van een functie

import time

def timer(func):
  """Een decorator die print hoe lang een functie duurde.

  Args:
    func (callable): De te decoreren functie.

  Returns:
    callable: De gedecoreerde functie.
  """
Functies schrijven in Python
import time

def timer(func):
  """Een decorator die print hoe lang een functie duurde."""

# 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
Functies schrijven in Python

timer() gebruiken

@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
Functies schrijven in Python
def memoize(func):
  """Sla resultaten van de gedecoreerde functie op voor snelle 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
Functies schrijven 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
Functies schrijven in Python

Wanneer decorators gebruiken

  • Voeg gemeenschappelijk gedrag toe aan meerdere functies
@timer
def foo():
  # do some computation

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

@timer
def baz():
  # do something else
Functies schrijven in Python

Laten we oefenen!

Functies schrijven in Python

Preparing Video For Download...