Re: from-import vs. import

Guido.van.Rossum@cwi.nl
Wed, 13 Jul 1994 11:35:30 +0200

Mike Tibbs asks:

> What's the difference between
>
> import strop
> and
> from strop import *

If you were to enter these statements interactively and inspect the
namespace with dir(), you would see the difference immediately:

(1)

>>> import strop
>>> dir()
['__name__', 'strop']
>>>

(2)

>>> from strop import *
>>> dir()
['__name__', 'atof', 'atoi', 'atol', 'index', 'joinfields', 'lower', 'lowercase', 'rindex', 'split', 'splitfields', 'strip', 'swapcase', 'upper', 'uppercase', 'whitespace']
>>>

In other words, (1) "import strop" introduces the name "strop" into
the namespace, while (2) "from strop import *" introduces each
individual object into it.

In case (1), to use the split() function, you can call
"strop.split(...)".

('__name__' is a variable that contains the name of the current
module, and is predefined in each module.)

Note that, as a matter of style, you shouldn't be importing "strop" --
this is really an "internal" module. The official interface is
"string", which provides some additional functions and compatibilities
with Python versions that don't implement "strop" yet. Once you have
imported string, there is NO additional performance penalty over using
strop -- whether you use "from string import *" or "import string".

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
<URL:http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>