Should Python import statements always be at the top of a module?

Posted by Adam J. Forster on Stack Overflow See other posts from Stack Overflow or by Adam J. Forster
Published on 2008-09-24T17:21:47Z Indexed on 2010/04/04 5:13 UTC
Read the original article Hit count: 319

Filed under:
|
|

PEP 08 states:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

However if the class/method/function that I am importing is only used in rare cases, surely it is more efficient to do the import when it is needed?

Isn't this:

class SomeClass(object):

    def not_often_called(self)
        from datetime import datetime
        self.datetime = datetime.now()

more efficient than this?

from datetime import datetime

class SomeClass(object):

    def not_often_called(self)
        self.datetime = datetime.now()

© Stack Overflow or respective owner

Related posts about python

Related posts about optimization