Skip to content

Collection to Bool

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: collection-to-bool

Section titled “Sourcery refactoring id: collection-to-bool”

Replace constant collection with boolean in boolean contexts

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

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