Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #106451
| Newsgroups | comp.lang.python |
|---|---|
| Date | 2016-04-04 08:59 -0700 |
| References | <570288d0$0$19758$426a74cc@news.free.fr> |
| Message-ID | <0bf822be-6eec-4a88-acd2-e0f17cab3b30@googlegroups.com> (permalink) |
| Subject | Re: module alias in import statement |
| From | Ned Batchelder <ned@nedbatchelder.com> |
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.
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
module alias in import statement "ast" <nomail@com.invalid> - 2016-04-04 17:31 +0200
Re: module alias in import statement Ned Batchelder <ned@nedbatchelder.com> - 2016-04-04 08:59 -0700
Re: module alias in import statement Steven D'Aprano <steve@pearwood.info> - 2016-04-05 02:15 +1000
Re: module alias in import statement Terry Reedy <tjreedy@udel.edu> - 2016-04-04 16:46 -0400
Re: module alias in import statement Rustom Mody <rustompmody@gmail.com> - 2016-04-04 21:08 -0700
Re: module alias in import statement Chris Angelico <rosuav@gmail.com> - 2016-04-05 14:23 +1000
Re: module alias in import statement Rustom Mody <rustompmody@gmail.com> - 2016-04-04 21:27 -0700
Re: module alias in import statement Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2016-04-05 17:26 +1000
Re: module alias in import statement Chris Angelico <rosuav@gmail.com> - 2016-04-05 17:47 +1000
csiph-web