Python模块对象称不可变却可改属性,为何能作字典键?
Great question—this is a common point of confusion because "immutability" here is a bit nuanced compared to what we usually think of with strings or tuples. Let's unpack this clearly:
1. What "immutable" means for module objects (per Mark Lutz)
When the book says module objects are immutable, it's referring to their core identity and hash value, not their ability to have attributes added or modified.
- A module's identity is tied to its memory address (returned by
id(module)), which never changes once the module is loaded into memory. - The hash value of a module (calculated via
hash(module)) is derived from this identity, so it stays constant for the entire lifetime of the module object.
This stability is what makes modules hashable—and hashability is the key requirement for being a dictionary key.
2. Why you can still add attributes to modules
Adding an attribute like b.additionalProperty = 'hello' doesn't alter the module object itself. Instead, you're just modifying the module's internal attribute dictionary (accessible via b.__dict__).
Think of the module object as a container: you can put new items into the container, but the container itself (the module instance in memory) remains the same. This doesn't affect its identity or hash value, so it still works perfectly as a dictionary key.
3. Quick comparison to clarify
To contrast:
- Mutable objects like lists can't be dictionary keys because their hash value changes when their contents change.
- Modules, even though you can modify their attributes, have a fixed hash value tied to their identity—so they meet the hashability rule for dictionary keys.
So the book's statement holds up: modules are "immutable" in the sense that their core identity (and thus hashability) never changes, which is what matters for being a dictionary key.
内容的提问来源于stack exchange,提问作者Thor

