tags:

views:

232

answers:

5

I apologize in advance if this question seems remedial.

Which would be considered more efficient in Python:

Standard import

import logging

try:
  ...some code...
exception Exception, e:
  logging.error(e)

...or...

Contextual import

try:
  ...some code...
exception Exception, e:
  import logging
  logging.error(e)
+2  A: 

They're essentially the same. The Python interpreter will only load a used module once, no matter how many times you import it. Changing the location of the import statement only has an effect on where the name is bound -- for example, if your import statement is inside a function, the name can only be used in that function.

Generally, though, imports are usually done as close to the "top" of a file as possible.

mipadi
Although in the example given, the difference for the contextual import is the module is -only- loaded if the exception occurs.
Matthew Trevor
+5  A: 

Contextual imports are technically more efficient, but I think they can create other problems.

Later, if you want to add a similar except clause, you now have two places to maintain the same block of code. You also now have the problem of testing the exception, to make sure that the first import doesn't cause any unforeseen issues in your code.

JimB
They're only more efficient if they're used rarely or never.
S.Lott
True, I was making the assumption that the import would rarely happen, otherwise there wouldn't really be a point. Conditional imports, as you pointed out, can be a better idea, and are very common, especially when dealing with multiple library versions.
JimB
+3  A: 

It depends on how often you execute the contextual import.

An import statement requires checking to see if the module exists, which has a non-zero cost.

Lots of contextual imports will be a performance penalty for no real gain in simplicity. There's very little benefit, unless you are really sure that the import will be used rarely or never.

Contextual imports inside if statements make sense, especially when it's done at the top level, which means precisely once.

if someConfig:
    import this as bigDeal
else:
    import that as bigDeal
S.Lott
+3  A: 

This is a microoptimization. Don't worry about it.

fivebells
I would add a bit about only optimizing after profiling. (Otherwise, perfect answer)
Ali A
+1  A: 

The performance differences between these two approaches will be very small in practice. I have never seen a case where this has made a difference that was noticeable.

It is worth remembering that the python interpreter will only ever do the work of parsing the module once when it is 1st imported.

In general you will end up with more maintainable code it you just import all the modules you need at the top of the file.

Mark