Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify `if 'foo' in kwargs and kwargs['foo'] is True:`

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...

like image 847
nowox Avatar asked Feb 09 '23 08:02

nowox


2 Answers

dict.get is useful to avoid the KeyError when accessing a non-existent key:

if kwargs.get('foo'):

Or

if kwargs.get('foo', False):
like image 157
shx2 Avatar answered Feb 23 '23 18:02

shx2


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
like image 37
Tom Barron Avatar answered Feb 23 '23 18:02

Tom Barron