I’m using Visual Studio Code 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, Visual Studio Code/autopep8 moves all import statements before the code, so Python can’t find my local package.
import sys import localpackage sys.path.insert(0, '/path/to/packages')
How can I tell Visual Studio Code/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
The behavior you’re observing is likely due to how autopep8 organizes imports. By default, autopep8 tends to sort and organize imports in a specific way, which might not be suitable for your case.
To customize the behavior, you can use a configuration file or add specific comments in your code. In your case, you can use the --ignore option to ignore certain rules for specific lines.
--ignore
Here’s how you can achieve this:
Create a configuration file for autopep8. You can create a file named .autopep8 in the root of your project (or where your settings apply).
.autopep8
In the .autopep8 file, you can specify the --ignore option for the lines you want autopep8 to ignore. For example:
[autopep8] ignore = E402
The E402 error in autopep8 corresponds to “module level import not at top of file.”
E402
import sys # noinspection PyUnresolvedReferences sys.path.insert(0, '/path/to/packages') import localpackage
The # noinspection PyUnresolvedReferences comment is a common way to indicate to tools like autopep8 or linters that the line following it should not be reported as an error.
# noinspection PyUnresolvedReferences
Choose the method that fits better into your workflow. Both options allow you to customize autopep8’s behavior for specific lines in your code.