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

Is it possible to simplify the boolean check of an option kwargs?

For example, fooI need to check a lot of parameters:

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 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 that does not contain patterns ...

+4
source share
3 answers

dict.getIt is useful to avoid KeyErrorwhen accessing a nonexistent key:

if kwargs.get('foo'):

Or

if kwargs.get('foo', False):
+6
source

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
+1
source

, , - get(), None . is True:

  • , ; ( python)

    kwargs.get( "foo" ):   ...

  • is Truenot only redundant, but also incorrect: it isdoes not check the equality of values, but the identifier. Any nonzero value is considered true in python, but, for example, 1 is Truecomes out as a lie! 1 == Truechecks the "truth", and this is what you should use (if anything). Even if this function will only receive true Booleans, it is a bad idea to burden your code with unnecessary strong assumptions about what it sees.

+1
source

Source: https://habr.com/ru/post/1618812/


All Articles