module alias in import statement

Chris Angelico rosuav at gmail.com
Tue Apr 5 03:47:29 EDT 2016


On Tue, Apr 5, 2016 at 5:26 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
>>> 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;
>>
>> Following looks like a cache miss to me (certainly did to the OP):
>>
>> On Monday, April 4, 2016 at 9:01:41 PM UTC+5:30, ast wrote:
>>> hello
>>>
>>> >>> import tkinter as tk
>>> >>> import tk.ttk as ttk
>>>
>>> Traceback (most recent call last):
>>>   File "<pyshell#3>", line 1, in <module>
>>>     import tk.ttk as ttk
>>> ImportError: No module named 'tk'
>
>
> But that *miss* isn't cached -- if the OP then created a package called "tk"
> with a submodule called "ttk", and then re-ran the `import tk.ttk as ttk`
> line, the import subsystem would have picked up the newly created package
> and imported it.
>
> I think that's the point Chris was trying to make.

Not quite; that was a separate point (that negative results aren't
cached). A cache miss is when the cache doesn't have something, and
Python goes to the next source (in this case, searching the file
system). The end result should be the same in either case (you get a
module object), but in Python, a cache miss results in *actual code
execution*. Granted, you often still won't *see* any difference (your
typical module just quietly defines a bunch of stuff), but there's
still a significant semantic difference; consider what happens when
you type "import this as that" followed by "import this". The second
one is a cache hit, and it's fundamentally different in function.

Cache invalidation is all about knowing when you should *ignore* the
cached entry and go back to the file system. Python will never do
this, because the semantics are defined very differently.

ChrisA



More information about the Python-list mailing list