简体   繁体   中英

python validate input with decorator for functions with varying inputs

I have many functions that all expected config as a parameter but vary with regards to other parameters. I would like to validate config . I wrote another function for this, but seems a decorator might be a cleaner solution:

def validate_config(config):
    if config not in [1,2,3]:
        raise ValueError("config is expected to be 1, 2 or 3")

def f1(config, b):
    validate_config(config)
    pass

def f2(a, config):
    validate_config(config)
    pass

you need get function paraments name at runtime, Fortunately, python can do this in easy way

use module inspect https://docs.python.org/3/library/inspect.html#inspect.BoundArguments.apply_defaults

import functools
import inspect


def validate_config(func):
    def wrapper(*args, **kwargs):
        sig = inspect.signature(func)
        ba = sig.bind(*args, **kwargs)
        ba.apply_defaults()
        print("config:", ba.arguments["config"])
        return func(*ba.args, **ba.kwargs)

    return functools.update_wrapper(wrapper, func)


@validate_config
def foo(config, b):
    pass


foo("this_is_config", 123)

But it's not a good idea to rely on parameter names

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM