Skip to content

Instantly share code, notes, and snippets.

@santiagobasulto
Last active August 5, 2018 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santiagobasulto/5fff2cb1d0a9cc9567c883bc440a859c to your computer and use it in GitHub Desktop.
Save santiagobasulto/5fff2cb1d0a9cc9567c883bc440a859c to your computer and use it in GitHub Desktop.
import functools
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def check_only_integers(fn):
"""Very simple decorator that prevents other than integers to be passed
to the decorated function. Just for demonstration purposes.
"""
@functools.wraps(fn)
def wrapped(*args):
if not all([type(arg) == int for arg in args]):
raise ValueError("Invalid param is not an integer")
return fn(*args)
return wrapped
class CheckOnlyIntegers:
def __init__(self, fn):
self.fn = fn
def __call__(self, *args):
if not all([type(arg) == int for arg in args]):
raise ValueError("Invalid param is not an integer")
return self.fn(*args)
# @check_only_integers # (this decorator does work)
@CheckOnlyIntegers
def add(x, y):
return x + y
# Tests:
assert add(2, 3) == 5
assert add(9, 11) == 20
with ProcessPoolExecutor() as ex: # Switch to ThreadPoolExecutor and it works!
future = ex.submit(add, 2, 3)
print(future.result())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment