module alias in import statement

Steven D'Aprano steve at pearwood.info
Mon Apr 4 12:15:34 EDT 2016


On Tue, 5 Apr 2016 01:31 am, 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'
> 
> 
> of course
> 
>>>> import tkinter.ttk as ttk
> 
> works
> 
> Strange, isn't it ?

No. You have to understand what the import statement does.

"import tkinter" does at least three steps:

- locate a Python file called (for example) "tkinter.py", 
  or a package "tkinter/__init__.py"
- execute that module or package file to create a module object
- create a local variable "tkinter" bound to the module object.

In pseudo-code:

# import tkinter
path = find module("tkinter")
tkinter = execute(path)


"import tkinter as tk" changes the last step:

# import tkinter as tk
path = find module("tkinter")
tk = execute(path)


Running "import tkinter as tk" doesn't change the name of the module or
package on disk. It doesn't change (say) the directory "tkinter/" to "tk/".


What happens if there is a dot in the module name?

"import tkinter.ttk as ttk" is similar to above:

- first import the package "tkinter"
- then import the submodule "ttk" inside that package.

In other words:

- locate a directory called "tkinter", containing a file called
  "__init__.py"; this is the package;
- execute that file "tkinter/__init__.py" to create a module object
- create a local variable "tkinter" bound to that module object

- then locate the module or subpackage "ttk" inside that same 
  directory;
- execute that file "tkinter/ttk.py" (for example" to create a 
  module object;
- create a local variable "ttk" bound to that module object.



So you can see why this doesn't work:


import tkinter as tk
import tk.ttk as ttk


is looking for a directory on disk called "tk", which doesn't exist. The
name "tk" is only local to your code, it doesn't rename the directory on
disk.



The real import statement is much more complicated than this, but as a
simplified description, I hope this helps.


-- 
Steven




More information about the Python-list mailing list