Created
November 9, 2021 14:43
-
-
Save AndrewOwenMartin/f51ac8192fb06096ed50f581cdabec75 to your computer and use it in GitHub Desktop.
Example of a Python decorator which accepts parameters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
import inspect | |
# my_meta = { | |
# "a": "ay", | |
# "b": "bee", | |
# } | |
# | |
# | |
# def metadecorator(name, meta=None): | |
# def decorator_name(func): | |
# @functools.wraps(func) | |
# def wrapper(*args, **kwargs): | |
# if meta is not None and name in meta: | |
# return meta[name] | |
# else: | |
# return func(*args, **kwargs) | |
# | |
# return wrapper | |
# | |
# return decorator_name | |
# | |
# | |
# @metadecorator(meta=my_meta, name="foobz") | |
# def my_foo(): | |
# return "fooby" | |
# | |
# | |
# def my_bar(a, b): | |
# return (a, b) | |
# | |
# | |
# print("my_foo", my_foo()) | |
# | |
# | |
# print("my_bar", my_bar("a", "b")) | |
# | |
# meta_my_bar = metadecorator(name="b", meta=my_meta)(my_bar) | |
# | |
# print("meta_my_bar", meta_my_bar("a", "b")) | |
# | |
# print(metadecorator(name="b", meta=my_meta)(my_bar)("aa", "bb")) | |
def generic_respect_required_args(required_kwargs): | |
def outer_wrapper(function): | |
@functools.wraps(function) | |
def wrapper(*args, **kwargs): | |
parameters = inspect.signature(function).parameters | |
all_args = dict(zip(parameters, args), **kwargs) | |
for required_kwarg in required_kwargs: | |
if all_args.get(required_kwarg) is None: | |
return None | |
return function(*args, **kwargs) | |
return wrapper | |
return outer_wrapper | |
import logging | |
log = logging.getLogger("loggy") | |
logging.basicConfig(level=logging.DEBUG) | |
@generic_respect_required_args(required_kwargs=['a','b']) | |
def my_fun(a, b=None, c=7): | |
return (a, b, c) | |
log.info(my_fun(1, 2, 3)) | |
log.info(my_fun(a=1, b=2, c=3)) | |
log.info(my_fun(a=1, b=2, c=None)) | |
log.info(my_fun(None, b=1, c=1)) # | |
log.info(my_fun(1, None, c=1)) # | |
log.info(my_fun(1, 2, None)) | |
log.info(my_fun(1, 2, c=None)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment