Skip to content

Collection to Bool

Sourcery refactoring id: collection-to-bool

Description:

Replace constant collection with boolean in boolean contexts

Before:

if ("foo", "bar"):
    baz()

After:

if True:
    baz()

Explanation:

In boolean contexts, dicts, lists, sets and tuples are true if they contain at least one element, and false if they are empty. Because of this, constant collections can be converted to bools based on their length. Some examples are:

  • []: empty list -> False
  • {}: empty dictionary -> False
  • {0, 1, 2}: non-empty set -> True
  • (a, b): non-empty tuple -> True