Matt
Matt

Reputation: 3848

Python if key in kwargs and key is true

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.

Upvotes: 4

Views: 7400

Answers (3)

Rick
Rick

Reputation: 45281

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):

Upvotes: 8

Ethan Bierlein
Ethan Bierlein

Reputation: 3535

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'):

Upvotes: 6

Emanuele Paolini
Emanuele Paolini

Reputation: 10162

A better way:

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

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

Upvotes: 3

Related Questions