is or is not compares with a literal

tx0/python:is-literaldefaultwarningbug

What it finds

x is 1, name is not "main": is compares identity, and whether two equal strings, numbers or tuples are the same object depends on the interpreter and on how the values were made. CPython warns about such comparisons when it compiles them. A list, dict or set written in place, as in x is [], is a new object and never identical to anything, so the comparison has a fixed result.

The fix for a literal replaces is with == and is not with !=. It is offered as unsafe, since the other operand may define equality in its own way.

From the rule's source, is_literal.rs.

Example from the rule's tests
def check(x, name, items):    if x is 1:tx0 reports: use == to compare with the int 1        pass    if name is not "main":tx0 reports: use != to compare with the string        pass    if b"data" is x:tx0 reports: is compares identity; use == to compare with the bytes        pass    if x is -1.5:tx0 reports: the float -1.5        pass    if x is 2j:tx0 reports: the complex number 2j        pass    if x is (1, 2.0):tx0 reports: the tuple (1, 2.0)        pass    if x is ():tx0 reports: the tuple ()        pass    if items is []:tx0 reports: this comparison is always false, since [] is a new list        pass    if items is not {}:tx0 reports: this comparison is always true, since {} is a new dict        pass    if x is None or x is True or x is ...:        pass    if x is f"{name}" or x is (1, name) or x is name:        pass    if x == 1 or x is not None:        pass
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/python:is-literal" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

# tx0: ignore[tx0/python:is-literal] reason="..."

tx0 explain tx0/python:is-literal shows the same in the terminal. Found a false positive? Report it.