Python Glossary Русский

all Python 3Conditionalsconstruct

is / is not

identity

The identity operators. They check whether two variables point at ONE object in memory. Use is/is not to test for None, True and False — not ==.

Syntax

a is b | a is not b

CPython pre-caches small integers (roughly -5 to 256) and some strings, so is may return True for them by accident — while the same check on larger numbers suddenly gives False. Hence the rule: use is only for None and other singletons, and compare ordinary values (numbers, strings, lists) with ==.

Examples

print(None is None)  # → True
x = None
print(x is None)  # → True (правильная проверка)
print(x == None)  # → True (работает, но стиль PEP8 — is)
a = [1, 2]; b = a
print(a is b)  # → True (одна ссылка)
c = [1, 2]
print(a is c)  # → False (разные объекты с одинаковым значением)
print(a == c)  # → True (равные по значению)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy