importing

Chris Angelico rosuav at gmail.com
Mon Mar 7 11:08:04 EST 2016


On Tue, Mar 8, 2016 at 2:54 AM, Tony van der Hoff <tony at 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.



More information about the Python-list mailing list