Is it possible to simplify the boolean check of a kwargs
option?
For example in foo
I have to check lots of options:
def foo(*args, **kwargs):
if 'foo' in kwargs and kwargs['foo'] is True:
do_something()
if 'bar' in kwargs and kwargs['bar'] is True:
do_something_else()
...
One possible workaroud is to hide some complexity by adding more complexity...
def parse_kwargs(kwords, **kwargs):
keywords = {}
for kw in kwords:
keywords[kw] = True if kw in kwargs and kwargs['kw'] is True else False
return keywords
Then in my main function:
def foo(*args, **kwargs):
kw = parse_kwargs(**kwargs)
if kw['foo']:
do_something()
if kw['bar']:
do_something_else()
...
I would like to know if I can use a simpler method less boilerplate...
dict.get
is useful to avoid the KeyError
when accessing a non-existent key:
if kwargs.get('foo'):
Or
if kwargs.get('foo', False):
How about this?
def foo(*args, **kwargs):
keywords = {'foo': do_foo_something,
'bar': do_bar_something,
'frug': do_frug_someting,
...}
for k in keywords:
if kwargs.get(k, False):
keywords[k]()
def do_foo_something():
do stuff
def do_bar_something():
do stuff
def do_frug_something():
do stuff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With