Python if key in kwargs and key is true

蓝咒 提交于 2019-12-11 03:35:18

问题


if 'force' in kwargs and kwargs['force'] is True:

It feels like there should be a better way of writing this condition since I'm repeating both the key and variable.


回答1:


While @EmanuelePaolini provided a great answer, there's another thing that I want to nitpick. You don't need to to check if something is true. For example, your code block would become this:

if 'force' in kwargs and kwargs['force']:

And @EmanuelePaolini's solution would become this:

if kwargs.get('force'):



回答2:


Assuming you really do want to check if the returned keyword argument is True, here's another slightly different way:

if kwargs.get('force', False) is True:

I think adding the False argument is a little bit more explicit/clear to the reader.

Using the above, EVERY value returned by the get method will cause the clause to be skipped except for when it contains a value of True.

However, Python is very nice when it comes to type casting to boolean - very often it simply isn't necessary to explicitly check is True. If this is the case, you can simply do this:

if kwargs.get('force', False):

Doing it this way, the statement reduces to if False in only a handful of cases. Here are some of them (possibly not all - though the docs says this covers all of them):

  • False
  • None - Python's null value
  • [], (), {}, set() - an empty container like a list, tuple, dict, or set
  • '' or "" - an empty string
  • 0, 0.0 - any numerical that is equivalent to zero
  • instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.

In this case, EVERY value returned by the get method will cause the clause to be executed except for when it contains a value that evaluates to False, such as one of the examples above. Any other value will evaluate to True. (Side note: containers that contain values which evaluate to False nonetheless evaluate to True, e.g., [None, None] or (0, 0) or {False, False}; this can be unexpected for inexperienced Python users).

If you want the key added to kwargs with a value of False at the point in time you check for it:

if kwargs.setdefault('force', False):



回答3:


A better way:

if kwargs.get('force') is True:

relies on the fact that kwargs.get('force') is None if 'force' not in kwargs'.



来源:https://stackoverflow.com/questions/31683724/python-if-key-in-kwargs-and-key-is-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!