module alias in import statement

Ned Batchelder ned at nedbatchelder.com
Mon Apr 4 11:59:10 EDT 2016


On Monday, April 4, 2016 at 11:31:41 AM UTC-4, 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 ?

Yes, I can see that seeming strange.  There are two things to know about
how imports work that will help explain it:

First, import statements are really just special syntax for an assignment.
When you say "import tkinter as tk", it means (in pseudocode):

    tk = __import__("tkinter")

The module named "tkinter" is sought, and when found, executed, and the
resulting module object is assigned to the name "tk".

Second, notice that "import tkinter" doesn't try to evaluate "tkinter" as
an expression. If it did, that import would raise an error, because "tkinter"
isn't defined.

So in your code, you defined the name "tk" in the first line, but that
doesn't mean the name "tk" is available for you to use in the second line.

--Ned.



More information about the Python-list mailing list