非容器成员资格测试¶
ID: py/member-test-non-container
Kind: problem
Security severity:
Severity: error
Precision: high
Tags:
- reliability
- correctness
Query suites:
- python-security-and-quality.qls
成员资格测试,即带有 in
或 not in
作为操作符的二元表达式,期望操作符右侧的表达式将是一个容器。
除了标准容器,如 list
、tuple
、dict
或 set
之外,容器可以是任何具有 __contains__
、__iter__
或 __getitem__
方法的类的实例。
建议¶
确保表达式的右侧是一个容器,或者为其他情况添加保护子句。例如,如果右侧可能是一个容器或 None
,则将 if x in seq:
更改为 if seq is not None and x in seq:
示例¶
在此示例中,NotAContainer
类没有 __contains__
、__iter__
或 __getitem__
方法。因此,当执行 if 2 in cont:
行时,将引发 TypeError。向 NotAContainer
类添加 __getitem__
方法将解决此问题。
class NotAContainer(object):
def __init__(self, *items):
self.items = items
def main():
cont = NotAContainer(1, 2, 3)
if 2 in cont:
print("2 in container")
参考¶
Python: 成员资格测试详情.
Python: contains 方法.