Should Import Statements Always Be At the Top of a Module

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

Module importing is quite fast, but not instant. This means that:

  • Putting the imports at the top of the module is fine, because it's a trivial cost that's only paid once.
  • Putting the imports within a function will cause calls to that function to take longer.

So if you care about efficiency, put the imports at the top. Only move them into a function if your profiling shows that would help (you did profile to see where best to improve performance, right??)


The best reasons I've seen to perform lazy imports are:

  • Optional library support. If your code has multiple paths that use different libraries, don't break if an optional library is not installed.
  • In the __init__.py of a plugin, which might be imported but not actually used. Examples are Bazaar plugins, which use bzrlib's lazy-loading framework.

Is it pythonic to import inside functions?

In the long run I think you'll appreciate having most of your imports at the top of the file, that way you can tell at a glance how complicated your module is by what it needs to import.

If I'm adding new code to an existing file I'll usually do the import where it's needed and then if the code stays I'll make things more permanent by moving the import line to the top of the file.

One other point, I prefer to get an ImportError exception before any code is run -- as a sanity check, so that's another reason to import at the top.

I use pyChecker to check for unused modules.

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

PEP 8 authoritatively states:

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

PEP 8 should be the basis of any "in-house" style guide, since it summarizes what the core Python team has found to be the most effective style, overall (and with individual dissent of course, as on any other language, but consensus and the BDFL agree on PEP 8).

In which cases is it acceptable to put imports not on the top in Python?

If you have a python program that has different paths, and only one of the paths use a specific module, you can import the module in that specific path. So you won't be importing many module you won't use.

Python - Does it matter if i import modules before or after defining functions? Newb Ques

It's a common use to make all imports on top, mainly for readability: you shouldn't have to look around the whole code to find an import. Of course you have to import a symbol before you can use it.

Anyway in Python it's not always wrong to import inside functions or classes, this is because of the way Python actually interpret the import. When you import a module you are actually running it's code, that is, in most cases, just defining new symbols, but could be also to trigger some side effect; thus it sometimes make sense to import inside functions to make the imported code execute only on function call.

Import statement inside class/function definition - is it a good idea?

It's the most common style to put every import at the top of the file. PEP 8 recommends it, which is a good reason to do it to start with. But that's not a whim, it has advantages (although not critical enough to make everything else a crime). It allows finding all imports at a glance, as opposed to looking through the whole file. It also ensures everything is imported before any other code (which may depend on some imports) is executed. NameErrors are usually easy to resolve, but they can be annoying.

There's no (significant) namespace pollution to be avoided by keeping the module in a smaller scope, since all you add is the actual module (no, import * doesn't count and probably shouldn't be used anyway). Inside functions, you'd import again on every call (not really harmful since everything is imported once, but uncalled for).

PEP8 – import not at top of file with sys.path

Often I have multiple files with tests in a subdirectory foo/tests of my project, while the modules I'm testing are in foo/src. To run the tests from foo/tests without import errors I create a file foo/tests/pathmagic.py that looks like this;

"""Path hack to make tests work."""

import os
import sys

bp = os.path.dirname(os.path.realpath('.')).split(os.sep)
modpath = os.sep.join(bp + ['src'])
sys.path.insert(0, modpath)

In every test file, I then use

import pathmagic  # noqa

as the first import. The "noqa" comment prevents pycodestyle/pep8 from complaining about an unused import.



Related Topics



Leave a reply



Submit