Allow statements before imports with Visual Studio Code and autopep8

  1. Open settings

  2. Search for autopep8. You should see the following results:

    Enter image description here

  3. Click on "Edit in settings.json" under the first option

  4. Add the following argument to the User Settings JSON file:

    "python.formatting.autopep8Args": ["--ignore", "E402"]
    

    Enter image description here

This tells autopep8 to ignore error 402 which is: "module level import not at top of file" (here's the list of errors in pep8)

You can use this same method to change any of the autopep8 settings. For example, if you only wanted to fix indentation, you can use "python.formatting.autopep8Args": ["--select", "E1"]

The autopep8 readme has more information on the available options.


If you don't want to generally disable import sorting, but just disable it for specific lines, you can use the following pragmas at the end of each line:

# noqa

or

# nopep8

Like so for your example:

import sys # noqa
sys.path.insert(0, '/path/to/packages') # noqa
import localpackage