"import foo" and "from foo import bar"

Thomas Wouters thomas at xs4all.net
Mon Jun 12 21:19:58 EDT 2000


On Tue, Jun 13, 2000 at 12:52:07AM +0000, Juanjo Álvarez wrote:

> I have a question regarding the difference between those two, apart from 
> having to type the module name before the symbol in the
> first case.

> If I am only using one or two simbols of a module (example: string): 

> It's better to write the "from string import join" form or it's exactly
> the same (in memory use and performance) that "import string"?

There certainly is a difference, but it isn't very large. Both statements
load the 'string' module into memory, both exactly in the same way. After
they load it in, the module shows up in sys.modules. The rest depends on
the exact statement.

'import string' does something like this:

string = sys.modules['string']

Whereas 'from string import join' does something like this:

join = sys.modules['string'].join

If there is any performance difference, it's going to be in the use of
'join'. If you use 'string.join' everywhere, Python will have to first look
for 'string', which will be in the global namespace, and then search that
for 'join'. If you use 'join' everywhere (either by using 'from string
import join' or by doing an explicit 'join = string.join') Python only has
to search the global namespace.

Of course, if you're that keen on performance, you probably want to pass
'join' into the functions that use it most, so that it gets turned into a
fast local variable index instead of a slow global namespace lookup ;)

Bottom line: In performance it has no real impact. Use whichever you deem
most readable: having to append a function or variable with the module name
can really clutter your code. On the other hand, by loading functions and
variables into your own namespace, you might shadow builtin functions or
variables (or worse, your own !) and cause great confusion when trying to
find out where a function came from.

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list