Saturday 5 September 2020

**kwargs and default arguments

 You can't pass the same argument twice, and variable=True, **kwargs does exactly that when kwargs contains a key for variable; in this case, you made the call effectively self.func(variable=True, variable=False) which is clearly wrong. Assuming you can't receive variable as a separate argument, e.g.:

def __init__(self, variable=True, **kwargs):
    self.func(variable, **kwargs)

then the other approach is to set the default in the kwargs dict itself:

def __init__(self, **kwargs):
    kwargs.setdefault('variable', True)  # Sets variable to True only if not passed by caller
    self.func(**kwargs)

In Python 3.5, with PEP 448's additional unpacking generalizations, you could one-line this safely as:

def __init__(self, **kwargs):
    self.func(**{'variable': True, **kwargs})

because repeated keys are legal when creating a new dict (only the last occurrence of a key is kept), so you can create a brand new dict with unique mappings, then immediately unpack it.


from : https://stackoverflow.com/questions/51940581/kwargs-and-default-arguments

No comments:

Post a Comment