5

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?

Community
  • 1
  • 1
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • Answers to the other questions all seem to cite PEP-8 as if it's somehow an answer all by itself, and they give few examples of where you *do* want imports elsewhere. – Glenn Maynard Mar 14 '11 at 18:02
  • (As for where to put global-level imports, yeah, at the top--but there's more to imports than that, which I think is worth explanation.) – Glenn Maynard Mar 14 '11 at 18:04
  • Another related question: http://stackoverflow.com/questions/1024049/is-it-pythonic-to-import-inside-functions – codeape Mar 14 '11 at 18:19

1 Answers1

10

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.

Glenn Maynard
  • 55,829
  • 10
  • 121
  • 131