Membership test with a non-container¶
ID: py/member-test-non-containerKind: problemSecurity severity: Severity: errorPrecision: highTags: - quality - reliability - correctnessQuery suites: - python-security-and-quality.qls
Click to see the query in the CodeQL repository
A membership test, that is a binary expression within ornotin as the operator, expects that the expression to the right of the operator will be a container.
As well as standard containers such aslist,tuple,dict orset, a container can be an instance of any class that has the__contains__,__iter__ or__getitem__ method.
Recommendation¶
Ensure that the right hand side of the expression is a container, or add a guard clause for other cases. For example, if the right side may be a container orNone then changeifxinseq: toifseqisnotNoneandxinseq:
Example¶
In this example theNotAContainer class has no__contains__,__iter__ or__getitem__ method. Consequently, when the lineif2incont: is executed a TypeError will be raised. Adding a__getitem__ method to theNotAContainer class would solve the problem.
classNotAContainer(object):def__init__(self,*items):self.items=itemsdefmain():cont=NotAContainer(1,2,3)if2incont:print("2 in container")
References¶
Python:Membership test details.
Python:Thecontains method.