I'm using vscode with the python plugin and autopep8 with
"editor.formatOnSave": true
.
I have local packages I need to import, so I have something like
import sys
sys.path.insert(0, '/path/to/packages')
import localpackage
but when I save, vscode/autopep8 moves all import statements before code, so python can't find my local package.
import sys
import localpackage
sys.path.insert(0, '/path/to/packages')
how can I tell vscode/autopep8 that it's okay to put a statement before imports, or is there a more correct way of importing local packages?
As a workaround it looks like it's fine if you import in an if statement
import sys
sys.path.insert(0, '/path/to/packages')
if 'localpackage' not in sys.modules:
import localpackage
- Open settings
- Search for autopep8. You should see the following results:
- Click on "Edit in settings.json" under the first option
- Add the following argument to the User Settings json:
"python.formatting.autopep8Args": ["--ignore", "E402"]
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 a specific line, you can use the following pragmas at the end of the line:
# noqa
or
# nopep8