Fundamentals 4 min read

Why Python’s Boolean Is Actually an Integer Subclass – Explained

An in‑depth look at why Python’s Boolean type is actually a subclass of int, covering object identities, the __base__ attribute, and the distinction between the ‘is’ and ‘==’ operators, complete with code screenshots and reference links for further reading.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Why Python’s Boolean Is Actually an Integer Subclass – Explained

1. Introduction

Hello, I’m PiPi. A few days ago a member of a Python community asked a basic question about the Python type system, as shown in the screenshot.

2. Implementation Details

The discussion concluded that the Boolean type in Python is a numeric type. The following code (shown in the image) demonstrates that bool and int share the same underlying type, but the objects True and 1 have different id values, meaning they are distinct objects.

Further screenshots show that bool is a subclass of int. Using the __base__ attribute confirms that the parent class of bool is int.

The article also clarifies the difference between the is operator and the == operator, illustrated by the following diagram.

3. Summary

This article reviews a basic Python type question, provides detailed analysis and code examples, and helps readers understand why Boolean values are considered numeric and how they relate to integers.

References: https://zhuanlan.zhihu.com/p/33907983, https://www.cnblogs.com/greatfish/p/6045088.html, https://mrcuriosity.org/python-string-intern.html.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

type-systemintbooleanprogramming fundamentalsequalityis-operator
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.