liveBook · Manning

Is operator

As explained in Python How-To

The identity operator is tests whether two references designate the same object.

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

How Python How-To covers it

How deep it goes
Defines identity versus value comparison and demonstrates both type checks and shared-list detection.
Examples
Demonstrates filter_tasks, type assertions, and copied Task objects sharing a tags list.
What you can do after
Diagnose shared mutable objects and distinguish identity checks from value comparisons.
How it connects
Connects object type comparison, equality, None, shallow copying, and deep copying.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.