Use is when the question is whether two references designate the same object. Use == when the question is whether two objects have the same value. section 10.3.2
Checking identity while filtering tasks
When a function accepts either an urgency list or an integer, compare the argument’s type with the class using is: if type(by_urgency) is list:. The list branch checks membership; the integer branch compares urgency values with ==. section 10.1.1
Listing 10.1 Comparing an object’s type with a class
def filter_tasks(tasks, by_urgency):
if type(by_urgency) is list:
filtered = [x for x in tasks if x.urgency in by_urgency]
else:
filtered = [x for x in tasks if x.urgency == by_urgency]
return filtered
A focused listing shows how is selects the list-handling branch while == performs the value comparison. section 10.1.1
Apply the operator in these situations:
- Compare an object’s type with a class, such as type(4) is int. section 10.1.1
- Compare a value with None using is; None is a singleton, so every use refers to the same object. section 10.3.2
- Detect shared mutable objects after a shallow copy: task.tags is task_copied.tags identifies the same list. section 10.3.2
