Welcome, guest | Sign In | My Account | Store | Cart

Python2.x implementation of python3's keyword-only arguments (aka arguments that must be specified as keywords, and are not automatically filled in by positional arguments - see PEP 3102).

Python, 26 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from functools import wraps


class default_kwargs(object):
    """
    Metadecorator for ensuring specified keys are present in kwargs before calling function

    Will only use default value if the key is not already present in kwargs.
    """
    def __init__(self, **kwargs):
        self.defaults = kwargs
    def __call__(self, wrapped):
        @wraps(wrapped)
        def wrapper(*args, **kwargs):
            new_kwargs = self.defaults.copy()
            new_kwargs.update(kwargs)
            return wrapped(*args, **new_kwargs)
        return wrapper


## Usage example:

@default_kwargs(echo=True)
def f(*args, **kwargs):
  if kwargs["echo"]:
    print args, kwargs