How can I conditionally set an attribute in the __init__
of a class, from a **kwargs
parameter?
I know that I can do:
default = 1
class foo():
def __init__(self, X=None, Y=None):
self.X = X if X else default
self.Y = Y if Y else default
F = foo()
f = foo(X=2, Y=3)
but I want to make this work with a variable-keyword parameter (**kwargs
), in order to understand them properly.
These attempts did not work:
default = 1
class foo():
def __init__(self, **kwargs):
self.X = default or kwargs['X']
self.Y = default or kwargs['Y']
F = foo()
f = foo(X=2, Y=3)
This way, only the default value is used even if other values are provided. If the order is switched (kwargs['X'] or default
etc.), the code raises a KeyError
if the keyword arguments are not provided.
default = 1
class foo():
def __init__(self, **kwargs):
self.X = value if kwargs["X"] is None else kwargs["X"]
self.Y = value if kwargs["Y"] is None else kwargs["Y"]
F = foo()
f = foo(X=2, Y=3)
This still raises a KeyError
for missing keyword arguments.