Skip to content

Instantly share code, notes, and snippets.

@huangsam
Last active January 17, 2020 17:38
Show Gist options
  • Save huangsam/4fc000c1c499abb3e0ae604e0375e189 to your computer and use it in GitHub Desktop.
Save huangsam/4fc000c1c499abb3e0ae604e0375e189 to your computer and use it in GitHub Desktop.
Testing decorator with parameter(s)
def approve(whitelist):
"""Bind whitelist arg to wrapper"""
def wrapper(func):
"""Bind old func to guard"""
def guard(*args, **kwargs):
"""Check if 'name' keyword matches whitelist"""
name = kwargs.get("name")
if name in whitelist:
print(f"=== approved {name}")
func(*args, **kwargs)
return True
else:
print(f"=== rejected {name}")
return False
return guard
return wrapper
@approve(whitelist={"johndoe", "marydoe"})
def hello(name):
print(f"Hello {name}")
assert hello(name="johndoe") is True
assert hello(name="marydoe") is True
assert hello(name="foobar") is False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment