[Tutor] Confused "from module import Name" better than "import module"?

Kent Johnson kent37 at tds.net
Mon Jul 11 19:44:26 CEST 2005


Matt Richardson wrote:
> I have a question about 'import module' versus 'from 
> module import name':  is there a performance hit to consider when 
> importing the entire module rather than just getting the specific 
> niceFunction()?

I can't imagine that there is a performance difference that would matter to any but the most time-critical application. Here is what happens in the two cases:

1.

import stuff
- loads module 'stuff' if this is the first import
- gets a reference to module stuff from sys.modules
- binds the name 'stuff' to module stuff in the global namespace of the current module

stuff.func()
- looks up 'stuff' in the local namespace, if any, which fails
- looks up 'stuff' in the global namespace which succeeds and yields module stuff
- looks up 'func' in the namespace of module stuff
- calls the function

2.

from stuff import func
- loads module 'stuff' if this is the first import
- gets a reference to module stuff from sys.modules
- looks up 'func' in the namespace of module stuff which yields function func
- binds the name 'func' to function func in the global namespace of the current module

func()
- looks up 'func' in the local namespace, if any, which fails
- looks up 'func' in the global namespace which succeeds and yields function func
- calls the function


So, at the point of import, plain 'import stuff' will be slightly faster because it doesn't lookup 'func' in the module.

At the point of call, 'from stuff import func' will be slightly faster because it has one less lookup.

This is good stuff to understand, but really, it isn't going to make an appreciable difference in most applications. Where it does matter, for example if func() is called many times in a loop, the best solution will probably be to bind func to a local variable which is the fastest to access.

Pick the style that you find most practical and readable and don't worry about efficiency.

Kent



More information about the Tutor mailing list