Common Mistakes Solved
Misunderstanding Object Identity
## Incorrect assumption
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) ## False, not the same object
graph TD
A[is Operator] --> B[Compares Memory Reference]
A --> C[Not Content Comparison]
A --> D[Use == for Value Comparison]
Incorrect None Checking
Bad Practice
def process_data(data):
## Incorrect None check
if data == None: ## Avoid this
return "No data"
Good Practice
def process_data(data):
## Recommended None check
if data is None: ## Preferred method
return "No data"
Integer Interning Misconceptions
Range |
Behavior |
Example |
-5 to 256 |
Interned |
a = 5; b = 5; a is b â True |
Outside Range |
Not Interned |
a = 257; b = 257; a is b â False |
## Surprising integer behavior
x = 256
y = 256
print(x is y) ## True
z = 257
w = 257
print(z is w) ## False
Floating Point and Object Identity
## Floating point comparison trap
a = 0.1 + 0.2
b = 0.3
print(a is b) ## False
print(a == b) ## True
String Interning Nuances
## String interning behavior
s1 = "hello"
s2 = "hello"
print(s1 is s2) ## Usually True
## Dynamic string creation
s3 = "hello" * 2
s4 = "hellohello"
print(s3 is s4) ## Not guaranteed
Function and Method Identity
class Example:
def method(self):
pass
obj1 = Example()
obj2 = Example()
## Method identity differs
print(obj1.method is obj2.method) ## False
Best Practices Checklist
graph TD
A[is Operator Best Practices] --> B[Use for None Checking]
A --> C[Avoid with Mutable Objects]
A --> D[Prefer == for Value Comparison]
A --> E[Understand Interning Limitations]
Key Recommendations:
- Use
is
for None
, True
, False
- Use
==
for value comparisons
- Be cautious with object identity checks
LabEx emphasizes understanding these subtle nuances to write more robust Python code.