import X vs from x import *

J. Cliff Dyer jcd at sdf.lonestar.org
Thu May 22 14:30:06 EDT 2008


On Thu, 2008-05-22 at 10:44 -0700, notnorwegian at yahoo.se wrote:
> import Tkinter
> from Tkinter import *
> 
> i have a program where if i comment out either of those import-
> statements i get an error.
> 
> i thought they meant the same thing and from was supposed to be just
> to imort just a specific function and the * imports everything in the
> module.
> but aparently the above statements have diffrent meaning and i cant
> figure it out fromt he tutorials.
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

Others have explained what one statement does as opposed to the other.

In general, you do not want to use from x import *.  Your namespace gets
polluted with all sorts of variables, and you don't know if you're going
to overwrite something important.  It's much better to specify which
names you want to import (for the sake of those reading your code later,
and for the sake of future-proofing your code against new variables
finding their way into the module being imported from), or just to
import the package (and optionally assign it to a shorter alias)

import Tkinter as tk

tk.function()

That said, there are occasional packages where it is common practice to
import *.  Tkinter might be one of those.  I don't have any experience
with it.  But don't make a habit of it. :)

Cheers,
Cliff





More information about the Python-list mailing list