[Tutor] Difference between >>> import modulex and >>> from moduleximport *?

don arnold darnold02 at sprynet.com
Sat Jan 3 08:01:10 EST 2004


----- Original Message -----
From: "Todd G. Gardner" <piir at earthlink.net>
To: "Tutor at Python. Org" <tutor at python.org>
Sent: Saturday, January 03, 2004 1:27 AM
Subject: [Tutor] Difference between >>> import modulex and >>> from
moduleximport *?


> Hello Everyone,
>
> I have some questions that I must have skipped the answers in the
tutorial.
> Pardon me if they are obvious.
>
> 1) What is the difference between ">>> import modulex" and ">>> from
modulex
> import *"?

'import modulex' imports everything in that module into a namespace called
'modulex'.
You then access that module's attributes (functions and variables) by using
the fully-
qualified identifier:

a = modulex.funca( )
b = modulex.someconst

'from modulex import *' pulls the module's contents into the current
namespace, so
you access them without a namespace qualifier:

a = funca( )
b = someconst

Although this might seem like a good way to save some typing, using 'from
modulex
import *' can lead to namespace pollution and conflicts. For example, if
modulea and
moduleb each define somefunction( ), this:

from modulea import *
from moduleb import *

a = somefunction( )

won't behave the same if you switch the order of the import statements. The
module
that was imported last will dictate which version of somefunction you 'see'.
You avoid
this problem when you leave the functions in their own namespaces:

import modulea
import moduleb

a1 = modulea.somefuntion( )
a2 = moduleb.somefunction( )


> 2) What happens when the command reads ">>> from modulex import
something"?

This works just like 'from modulex import *', except that the only
'something' gets imported
into the current namespace.

>     2a) Is something a function that is imported from modulex?

It's some attribute that modulex defined, whether it's a function or some
other object.

>
> Thank in advance,
>
> Thank you,
>
> Todd

HTH,
Don




More information about the Tutor mailing list