module alias in import statement

Chris Angelico rosuav at gmail.com
Tue Apr 5 00:23:09 EDT 2016


On Tue, Apr 5, 2016 at 2:08 PM, Rustom Mody <rustompmody at gmail.com> wrote:
>> 'import tk.ttk' looks for 'tk' in sys.modules, does not find it, looks
>> for a module named 'tk' on disk, does not find it, and says so.
>
> A well-known quote comes to mind:
>
> | There are only two hard things in Computer Science: cache invalidation and
> | naming things.
>
> eg. http://martinfowler.com/bliki/TwoHardThings.html
>
> particularly since this seems to be in both categories :-)

sys.modules isn't really a cache in that sense, though. The "hard
problem" of cache invalidation comes from the fundamental assumption
that a cache hit should be semantically identical to a cache miss;
Python's import system has fundamentally different semantics,
specifically that modules can exist independently of anything on the
disk, and modules are guaranteed to be singletons - which means that
"import decimal; decimal.getcontext().prec = 50" will affect anyone
else who uses the decimal module, because there can't be a duplicate.
(The one exception to this, where __main__ gets reimported under
another name, causes significant confusion despite being extremely
uncommon.)

If you like, you can look at sys.modules as a mandatory cache that
never records negatives and always records positives. Once an import
has succeeded, it will always be resolved from the cache, until
program termination; failed imports will always be retried. Python
dodges the cache invalidation problem by never invalidating anything
:)

ChrisA



More information about the Python-list mailing list