[Tutor] question about import statement

Hugo Arts hugo.yoshi at gmail.com
Fri Aug 27 07:05:55 CEST 2010


On Thu, Aug 26, 2010 at 11:18 PM, Greg Bair <gregbair at gmail.com> 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?
>

http://docs.python.org/tutorial/modules.html#importing-from-a-package

It's a practical thing, mostly for packages. When you import * from a
package 'x', how does python know all the modules present in the
package? You would hope that it somehow goes into the filesystem and
figures out all the files inside the 'x' directory, but this could
take a long time and have unwanted side-effects. So, you have to
specify the __all__ variable inside your __init__.py file, and that
way import * will know what to do. Alternatively, you can just import
all the modules inside __init__.py, since any names that are inside
__init__.py will also be loaded.

Hugo


More information about the Tutor mailing list