This rule raises an issue when a membership test using in or not in is performed on an empty collection literal such as
[], {}, set(), tuple(), or frozenset().
In Python, the membership operators in and not in test whether a value exists in a collection. When the collection is
empty, these tests always produce predictable results:
x in [] is always False because the value cannot exist in an empty collectionx not in [] is always True because the value is indeed not in an empty collectionThis pattern typically indicates one of three problems:
Consider this example:
if user_id in []:
grant_access()
This condition will never be true, so grant_access() will never be called. The code is either incomplete, meaning the list should
contain authorized user IDs, or the check is unnecessary and should be removed.
The issue applies to all Python collection types:
[]{}, which creates an empty dictionary, not a set. When used with in, it tests keys.set()() or tuple()frozenset()This issue can lead to bugs where conditions never evaluate as expected, causing:
The severity depends on the context. An authorization check that always fails could be a critical security issue, while a redundant check might only affect code maintainability.
If the collection should contain values, populate it with the appropriate elements before performing the membership test.
if user_id in []: # Noncompliant: empty list
grant_access()
if user_id in ["admin", "user123", "moderator"]:
grant_access()