Alex Rivera | Logout

Good or bad practice in Python: import in the middle of a file

Asked 2009-07-27T14:53:25.170
74

Suppose I have a relatively long module, but need an external module or method only once.

Is it considered OK to import that method or module in the middle of the module?

Or should imports only be in the first part of the module.

Example:

import string, pythis, pythat
...
...
...
...
def func():
     blah
     blah 
     blah
     from pysomething import foo
     foo()
     etc
     etc 
     etc
...
...
...

Please justify your answer and add links to PEPs or relevant sources

Edit
Report

3 Answers

13

If the imported module is infrequently used and the import is expensive, the in-the-middle-import is OK.

Otherwise, is it wise to follow Alex Martelli's suggestion.

answered 2009-07-27T14:59:13.913
8

It's generally considered bad practice, but sometimes it's unavoidable (say when you have to avoid a circular import).

An example of a time when it is necessary: I use Waf to build all our code. The system is split into tools, and each tool is implemented in it's own module. Each tool module can implent a detect() method to detect if the pre-requisites are present. An example of one of these may do the following:

def detect(self):
    import foobar

If this works correctly, the tool is usable. Then later in the same module the foobar module may be needed, so you would have to import it again, at function level scope. Clearly if it was imported at module level things would blow up completely.

answered 2009-07-27T14:57:40.233
7

It is considered "Good Form" to group all imports together at the start of the file.

Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global symbol table.

From here: http://docs.python.org/tutorial/modules.html

answered 2009-07-27T14:57:15.973

Your Answer