6.11. Object Identity¶
6.11.1. Rationale¶
=
assignment==
checks for object equalityis
checks for object identity
found = True
found == True
found is True
6.11.2. Identity¶
id(obj) -> int
id()
will change every time you execute scriptid()
returns an integer which is guaranteed to be unique and constant for object during its lifetimeTwo objects with non-overlapping lifetimes may have the same
id()
valueIn CPython it's also the memory address of the corresponding C object
id('Watney')
# 4499664048
hex(id('Watney'))
# '0x10c336cb0'
6.11.3. Value Comparison¶
==
checks for object equality
'Mark Watney' == 'Mark Watney'
# True
a = 'Mark Watney'
b = 'Mark Watney'
a == b
# True
6.11.4. Identity Check¶
is
checks for object identityis
comparesid()
output for both objectsCPython: compares the memory address a object resides in
Testing strings with
is
only works when the strings are internedSince Python 3.8 - Compiler produces a
SyntaxWarning
when identity checks (is
andis not
) are used with certain types of literals (e.g.str
,int
). These can often work by accident in CPython, but are not guaranteed by the language spec. The warning advises users to use equality tests (==
and!=
) instead.
'Mark Watney' is 'Mark Watney'
# <stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
# True
a = 'Mark Watney'
b = 'Mark Watney'
a is b
name = None
name is None
name is True
name is False
name = None
type(name) is int
type(name) is float
type(name) is complex
type(name) is bool
type(name) is None
type(name) is str
type(name) is bytes
type(name) is list
type(name) is tuple
type(name) is set
type(name) is frozenset
type(name) is dict
6.11.5. Problem¶
'Mark Watney' is 'Mark Watney'
# True
>>> a = 'Mark Watney'
... b = 'Mark Watney'
>>> a == b
True
>>> a is b
True
>>> a = 'Mark Watney'
>>> b = 'Mark Watney'
>>> a == b
True
>>> a is b
False
6.11.6. Compare Value and Identity¶
name = 'Mark Watney'
expected = 'Mark Watney'
name == expected
# True
name is expected
# False
name == 'Mark Watney'
# True
name is 'Mark Watney'
# False