Table of Contents
The 'is' Operator's Unexpected Behavior with Non-Cached Integers
Inquiry
Explanation
Code Demonstration
Notes
Home Backend Development Python Tutorial Why does the \'is\' operator behave differently with non-cached integers inside and outside a function in Python?

Why does the \'is\' operator behave differently with non-cached integers inside and outside a function in Python?

Oct 31, 2024 pm 07:22 PM

Why does the 'is' operator behave differently with non-cached integers inside and outside a function in Python?

The 'is' Operator's Unexpected Behavior with Non-Cached Integers

Inquiry

While experimenting with Python's interpreter, a paradox was noticed regarding the 'is' operator. Specifically, 'is' returns True when evaluated within a function but False when evaluated outside of it:

>>> def func():
...     a = 1000
...     b = 1000
...     return a is b
...

>>> a = 1000
>>> b = 1000
>>> a is b, func()
(False, True)
Copy after login

Since 'is' evaluates the object's 'id', this implies that within the 'func' function, 'a' and 'b' refer to the same int instance. However, outside of the function, they refer to different objects. Why is this the case?

Explanation

The Python reference manual offers an insightful clarification:

"A block is a piece of Python program text that is executed as a unit. Each command typed interactively is a block."

Within a function, a single code block exists, containing only one object for the number 1000. Thus, 'id(a)' and 'id(b)' return the same value, resulting in a True evaluation.

Outside of the function, we have two separate code objects, each with its object for 1000. Therefore, 'id(a)' and 'id(b)' are different, leading to a False evaluation.

This quirk is not exclusive to integers. Similar results are observed with, for instance, float literals. Remember, comparing objects for identity (using 'is') is generally discouraged; instead, the equality operator ('==') should be employed.

Code Demonstration

To gain a clearer understanding, we can delve into the code objects for both cases:

Within the 'func' Function:

>>> print(dis.code_info(func))
...
Constants:
   0: None
   1: 1000
Copy after login

We have a single 'int' instance for 1000 that is assigned to both 'a' and 'b'.

Outside the 'func' Function:

>>> com1 = compile("a=1000", filename="", mode="single")
>>> com2 = compile("b=1000", filename="", mode="single")
>>> id(com1.co_consts[0]) == id(com2.co_consts[0])
False
Copy after login

We see that each code object has its instance of 1000, leading to the False evaluation.

Notes

  • This observation pertains to CPython, the most widely used Python implementation.
  • Chained statements evaluate to True for 'is' because they are treated as a single code block.
  • Execution at the module level also yields True.
  • Identity checks using 'is' are not recommended for mutable objects, as they will always evaluate to False.

The above is the detailed content of Why does the \'is\' operator behave differently with non-cached integers inside and outside a function in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article

Hot Article

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Do I Use Beautiful Soup to Parse HTML? How Do I Use Beautiful Soup to Parse HTML? Mar 10, 2025 pm 06:54 PM

How Do I Use Beautiful Soup to Parse HTML?

Image Filtering in Python Image Filtering in Python Mar 03, 2025 am 09:44 AM

Image Filtering in Python

How to Download Files in Python How to Download Files in Python Mar 01, 2025 am 10:03 AM

How to Download Files in Python

Intro to Flask: Adding a Contact Page Intro to Flask: Adding a Contact Page Feb 28, 2025 am 10:03 AM

Intro to Flask: Adding a Contact Page

How to Use Python to Find the Zipf Distribution of a Text File How to Use Python to Find the Zipf Distribution of a Text File Mar 05, 2025 am 09:58 AM

How to Use Python to Find the Zipf Distribution of a Text File

How to Work With PDF Documents Using Python How to Work With PDF Documents Using Python Mar 02, 2025 am 09:54 AM

How to Work With PDF Documents Using Python

How to Cache Using Redis in Django Applications How to Cache Using Redis in Django Applications Mar 02, 2025 am 10:10 AM

How to Cache Using Redis in Django Applications

How to Perform Deep Learning with TensorFlow or PyTorch? How to Perform Deep Learning with TensorFlow or PyTorch? Mar 10, 2025 pm 06:52 PM

How to Perform Deep Learning with TensorFlow or PyTorch?

See all articles