Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Comparison using is when operands support__eq__

ID: py/comparison-using-isKind: problemSecurity severity: Severity: warningPrecision: highTags:   - quality   - reliability   - correctnessQuery suites:   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

When you compare two values using theis orisnot operator, it is the object identities of the two values that is tested rather than their equality. If the class of either of the values in the comparison redefines equality then theis operator may returnFalse even though the objects compare as equal. Equality is defined by the__eq__ or, in Python2,__cmp__ method. To compare two objects for equality, use the== or!= operator instead.

Recommendation

When you want to compare the value of two literals, use the comparison operator== or!= in place ofis orisnot.

If the uniqueness property or performance are important then use an object that does not redefine equality.

Example

In the first line of the following example the programmer tests the value ofvalue againstDEFAULT using theis operator. Unfortunately, this may fail when the function is called with the string"default".

To function correctly, change the expressionvalueisDEFAULT tovalue==DEFAULT. Alternatively, if the uniqueness property is desirable, then change the definition ofDEFAULT to either of the alternatives below.

DEFAULT="default"defget_color(name,fallback):ifnameinCOLORS:returnCOLORS[name]eliffallbackisDEFAULT:returnDEFAULT_COLORelse:returnfallback#This worksprint(get_color("spam","def"+"ault"))#But this does notprint(get_color("spam","default-spam"[:7]))#To fix the above code change to objectDEFAULT=object()#Or if you want better repr() output:classDefault(object):def__repr__(self):return"DEFAULT"DEFAULT=Default()

References


[8]ページ先頭

©2009-2025 Movatter.jp