What's the approved programming pattern for distributing keyword arguments among called functions?
Consider this contrived (and buggy) example:
def create_box(**kwargs):
box = Box()
set_size(box, **kwargs)
set_appearance(box, **kwargs)
def set_size(box, width=1, height=1, length=1):
...
def set_appearance(box, material='cardboard', color='brown'):
...
Obviously the set_size()
method will object to receiving material
or color
keyword arguments, just as set_appearance()
will object to receiving width
, height
, or length
arguments.
There's a valid argument that create_box()
should make all of the keyword and defaults explicit, but the obvious implementation is rather unwieldy:
def create_box(width=1, height=1, length=1, material='cardboard', color='brown'):
box = Box()
set_size(box, width=width, height=height, length=length)
set_appearance(box, material=material, color=color)
Is there a more Pythonic way to approach this?
You could add **kwargs
as the last argument to the functions that would otherwise become annoyed.
def create_box(**kwargs):
box = Box()
set_size(box, **kwargs)
set_appearance(box, **kwargs)
def set_size(box, width=1, height=1, length=1, **kwargs):
...
def set_appearance(box, material='cardboard', color='brown', **kwargs):
...