Timeout(): een praktijkvoorbeeld

Functies schrijven in Python

Shayne Miel

Software Architect @ Duo Security

Timeout


def function1():
  # Deze functie draait soms
  # heel lang door
  ...

def function2(): # Deze functie hangt soms # en geeft niets terug ...
Functies schrijven in Python

Timeout

@timeout
def function1():
  # Deze functie draait soms
  # heel lang door
  ...

@timeout def function2(): # Deze functie hangt soms # en geeft niets terug ...

stopwatch

Functies schrijven in Python

Timeout - achtergrondinfo

import signal

def raise_timeout(*args, **kwargs): raise TimeoutError()
# Wanneer een "alarm"-signaal afgaat, voer raise_timeout() uit signal.signal(signalnum=signal.SIGALRM, handler=raise_timeout)
# Zet over 5 seconden een alarm signal.alarm(5)
# Annuleer het alarm signal.alarm(0)
Functies schrijven in Python
def timeout_in_5s(func):

@wraps(func) def wrapper(*args, **kwargs):
# Stel een alarm in voor 5 seconden signal.alarm(5)
try: # Roep de gedecoreerde func aan return func(*args, **kwargs)
finally: # Annuleer alarm signal.alarm(0)
return wrapper
@timeout_in_5s
def foo():
  time.sleep(10)
  print('foo!')
foo()
TimeoutError
Functies schrijven in Python
def timeout(n_seconds):

def decorator(func):
@wraps(func) def wrapper(*args, **kwargs):
# Stel een alarm in voor n seconden signal.alarm(n_seconds)
try: # Roep de gedecoreerde func aan return func(*args, **kwargs) finally: # Annuleer alarm signal.alarm(0)
return wrapper
return decorator
@timeout(5)
def foo():
  time.sleep(10)
  print('foo!')

@timeout(20) def bar(): time.sleep(10) print('bar!')
foo()
TimeoutError
bar()
bar!
Functies schrijven in Python

Laten we oefenen!

Functies schrijven in Python

Preparing Video For Download...