Python,如果在kwargs中输入key并且key为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.

@EmanuelePaolini 提供了一个很好的答案,还有另外一件我想挑剔的事情.您无需检查是否为真.例如,您的代码块将变为:

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

@EmanuelePaolini的解决方案将变为:

if kwargs.get('force'):