Understanding Python Dictionary Keys, Return Behavior in try/finally, and Object Identity
This article explains why Python dictionary keys with numeric values can overwrite each other, how a return statement inside a try block is overridden by a return in a finally block, and why object identity (is) and hash values behave as they do, illustrating each point with code examples.
First, the article demonstrates that Python dictionaries treat numeric keys that are equal after type conversion (e.g., 5 and 5.0 ) as the same key, so later assignments overwrite earlier ones. Example code:
<code>some_dict = {}
some_dict[5.5] = "Ruby"
some_dict[5.0] = "JavaScript"
some_dict[5] = "Python"
</code>When queried, some_dict[5.5] returns "Ruby", while both some_dict[5.0] and some_dict[5] return "Python" because the integer and float keys are considered identical.
The article notes that Python determines key equality by comparing hash values and equality, and that immutable objects with the same value share the same hash, though hash collisions are possible.
Second, it shows that a return inside a try block is superseded by a return in the corresponding finally block. Example:
<code>def some_func():
try:
return 'from_try'
finally:
return 'from_finally'
</code>Calling some_func() yields 'from_finally' because the finally clause always executes and its return value becomes the function's result.
Third, the article explores object identity and hash behavior. It defines a simple class WTF and shows that two separate instances are not equal ( WTF == WTF is False ) and are not the same object ( WTF is WTF is False ), yet their hash values may be equal due to implementation details. It also explains that the id() function returns the memory address of an object, which is only unique for the object's lifetime; after an object is destroyed, the same address can be reused, leading to identical id values for distinct objects created at different times.
Finally, the article illustrates that the is operator returns False for two separate instances of WTF even though their id values can match after the first objects are garbage‑collected, highlighting the role of object destruction order in these differences.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.