如何证明Python中的布尔值(boolean)是不可变对象?
Great question! Let's walk through concrete, easy-to-follow ways to demonstrate that boolean objects (True/False) are immutable in Python. First, a quick recap: immutable objects are those whose state (value) can’t be modified after creation—any "change" you try to make actually creates a brand-new object instead of altering the original.
1. Track Object IDs to See "Modifications" Create New Objects
Every Python object has a unique identifier you can check with the id() function. For immutable types, reassigning a variable to a different value doesn’t tweak the original object—it just makes the variable point to a new one.
Try running this code:
# Assign a boolean to a variable my_bool = True print(f"ID of initial True: {id(my_bool)}") # "Change" the variable's value my_bool = False print(f"ID of new False: {id(my_bool)}")
You’ll see two completely different IDs. This proves we didn’t modify the original True object—we just redirected my_bool to reference the separate False singleton instead.
2. Attempt to Modify Boolean Attributes (It Will Fail)
Immutable objects block any attempt to add or modify their attributes after creation. Since bool inherits from int (another immutable type), trying to alter its properties throws a clear error:
test_bool = True test_bool.custom_attr = "hello" # This line will crash!
You’ll get an error message like:
AttributeError: 'bool' object has no attribute 'custom_attr'
This is a dead giveaway of immutability—Python actively prevents you from changing the object’s internal state or adding new properties.
3. Verify Booleans Are Singletons
Python only creates one instance of True and one instance of False across the entire interpreter. Every variable set to True points to the exact same object:
a = True b = True c = 1 == 1 # Evaluates to True print(a is b) # Output: True (same underlying object) print(a is c) # Output: True (also the same object)
If booleans were mutable, changing one True variable’s value would affect all others—but since you can’t modify the underlying True object itself, this is impossible. Any "change" just redirects the variable to a different singleton.
内容的提问来源于stack exchange,提问作者newbieeyo

