[Tutor] question about import statement

Peter Otten __peter__ at web.de
Fri Aug 27 09:45:39 CEST 2010


Greg Bair wrote:

> On 08/26/2010 10:29 PM, Hugo Arts wrote:
>> On Thu, Aug 26, 2010 at 9:16 PM, Bill Allen <wallenpb at gmail.com> wrote:
>>>
>>> I did try that and of course it gave an error because it was necessary. 
>>> I
>>> just did not know why.   However, I later found an explanation on the
>>> web. Here it is:
>>>
>>> from tkinter import *
>>> from tkinter import ttk
>>>
>>> These two lines tell Python that our program needs two modules. The
>>> first, "tkinter", is the standard binding to Tk, which when loaded also
>>> causes the existing Tk library on your system to be loaded. The second,
>>> "ttk", is Python's binding to the newer "themed widgets" that were added
>>> to Tk in 8.5.
>>>
>> 
>> yeah, "from package import *" doesn't actually import every name from
>> a module. For example, by default, names starting with an underscore
>> are not imported. Alternatively, if you have a variable named __all__
>> in your module, and it's a list of names, only those names in the list
>> actually get imported when you do a "from x import *"
>> 
>> Hugo
> Why would the person who wrote this package choose to do it this way,
> though?  If it was something that people would use and not just an
> internal name, why hide it this way?

There are many programs out there that don't use ttk. For those it would be 
a waste of time and memory if the tkinter.ttk module were imported 
automatically. If you modify your example to

from tkinter import *
root = Tk()
button = Button(root, text="Hello World").grid()
root.mainloop()

it will still work (but maybe look a little different). If the ttk import 
were automatic the above script might not work on machines that don't have 
"themed widgets" even though it doesn't use them. 

In general it is good practice that modules introduce as few dependencies as 
possible.

Peter



More information about the Tutor mailing list