Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it "more pythonic" to have all imports at the top, or on demand? [duplicate]

Tags:

python

import

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?

like image 331
ripper234 Avatar asked Jan 20 '23 06:01

ripper234


1 Answers

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.

like image 198
Glenn Maynard Avatar answered Jan 30 '23 02:01

Glenn Maynard