简体   繁体   中英

How can I add a required argument to existing python function using a decorator?

So, I would like to modify the json.loads() function to accept a new keyword parameter, but not have it just be a part of kwargs. In other words, I want it be an explicit part of the function's signature.

Here's my guess on how to do this. Are there better ways of doing this?

def json_to_python_syntax(json_method):
    """
    Translate JSON-conforming key names to Pythonic standards on dict.

    The goal of this decorator is to add a standard keyword parameter
    'convert_syntax' onto the method.  But, I'm not sure how to do this.

    """
    @wraps(json_method)
    def wrapper(json_string, convert_syntax=False, **kwargs):
        pythonic_dict = dict()
        json_syntax_dict = json_method(json_string, **kwargs)

        if not convert_syntax:
            return json_syntax_dict

        for key, value in json_syntax_dict.iteritems():
            for json_syntax in re.finditer(r'[A-Z]', key):
                key = key.replace(
                    json_syntax.group(), '_' + json_syntax.group()[0].lower())
            pythonic_dict[key] = value
        return pythonic_dict

    return wrapper

My concern with this method is that it this monkeys with the expected order of keyword parameters in json.loads (It makes convert_syntax the first expected parameter after the json string) and could mess up other calls to json.loads within the larger program that assume the standard order.

Seeing as your change breaks the expected signature of json.loads and you're concerned with it breaking other code that depends on the original signature, I'd agree with Simeon Visser, seems like you shouldn't do this at all.

Only code you write will be able to properly call your new method, so why not give your method a different name, rather than decorating an existing method? If you want to prevent other code from calling this method without the convert_syntax flag, just avoid importing the json module at all, and instead import your json library that wraps the json module.

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