C0415 import-outside-toplevel


'Import outside toplevel (%s)'


Used when an import statement is used anywhere other than the module toplevel. Move this import to the top of the file.


In the following example, we import sys within the function fn.

def fn():
    import sys
2:4: C0415: Import outside toplevel (sys)

This is not a good pratice. We should always have our import statements on the toplevel and at the top of the file.

import sys

def fn():
No issues found.


There are some exceptions to that rule:

  • If you have an import cycle, moving import statements into functions or methods can help. You should try to fix the cyclic import by merging or splitting modules though.

  • If you need to control the time when a module is imported (because it uses some global state that needs to be set up before), it is also OK to use non-toplevel imports.

Running Pylint locally? In your CI?

There is a better way! Run PyCodeQual & get Pylint findings with history, diffs and statistics.

Click here to find out more.