Possible Duplicate:
Good or bad practice in Python: import in the middle of a file
I'm used to languages like Java that mandate that all import
statements appear at the top of the class/file.
Which is considered more pythonic/"beautiful" - having them all at the top, or on demand, as they're needed?
It depends.
Most of the time you want it at the top. This isn't because of PEP-8 (anyone who cites PEP-8 as a justification in and of itself misunderstands design rationale), but for the practical reasons underlying PEP-8's recommendation:
If you put imports inside functions, and those imports aren't available, it's likely to hide problems. Instead of throwing an exception when your module is imported, it'll only happen when some function is called. It's also a bit less efficient, pulling in the name on demand, though that's usually minor.
However, this isn't a hard rule. You may want to import on demand with certain types of feature detection. For example,
def decode(s):
try:
import cjson
return cjson.decode(s)
except ImportError:
import simplejson
return simplejson.loads(s)
print decode('[1,2,3]')
or similarly,
try:
import cjson
def decode(s):
return cjson.decode(s)
except ImportError:
import simplejson
def decode(s):
return simplejson.loads(s)
print decode('[1,2,3]')
You may also specifically want to support certain method calls only if a module is available, without causing the whole module to depend on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With