Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #104220

Re: importing

From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Subject Re: importing
Date 2016-03-08 03:08 +1100
Message-ID <mailman.22.1457366891.10335.python-list@python.org> (permalink)
References <56DDA44B.7040405@vanderhoff.org>

Show all headers | View raw


On Tue, Mar 8, 2016 at 2:54 AM, Tony van der Hoff <tony@vanderhoff.org> wrote:
> I thought I understood this, but apparently not:
> Under py3:
>
> 1. "import tkinter" imports the whole module into the name space. Any access
> to names therein must be prefixed with the module name.
> ie top = tkinter.Tk()
> But tkinter.messagebox.showwarning()  errors with "module has no attribute
> 'messagebox'"

Your description is of a general module, but tkinter is actually a
package. Packages are slightly different, in that their modules might
not be loaded automatically. You can also do this:

import tkinter.messagebox

which is a syntax that works ONLY with packages. [1]

> 2. "from tkinter import *" loads the name space from the module into the
> program name space. No need to prefix the module name onto the attribute
> name. Pollutes the name space, but makes typing easier.
> ie top = Tk()
> But messagebox.showwarning() still errors.
>
> I imagined that the "*" form implied "load the lot". Evidently, my
> understanding is lacking. Will somebody please put me straight, or give me a
> reference to some definitive documentation?

Sorta-kinda. The star import means "load all the obvious names". Even
with non-package modules, it won't always import everything - if
there's a list of names in __all__, only those names will  be
imported. Generally, this means you don't get nested module references
(eg because a module did "import sys"), but it can do anything else as
well.

The documentation should tell you what you need to import to make
something work. In this case, I would guess that "import
tkinter.messagebox" or "from tkinter import messagebox" would be the
recommended way to use this module.

ChrisA

[1] Modulo os.path, which is done by injection. Ignore that.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: importing Chris Angelico <rosuav@gmail.com> - 2016-03-08 03:08 +1100

csiph-web