小能豆

Allow statements before imports with Visual Studio Code and autopep8

java

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

阅读 76

收藏
2023-11-23

共1个答案

小能豆

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.

Here’s how you can achieve this:

  1. Create a configuration file for autopep8. You can create a file named .autopep8 in the root of your project (or where your settings apply).

  2. 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.”

  1. Alternatively, you can add a comment in your code to instruct autopep8 to ignore specific lines. For example:

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.

Choose the method that fits better into your workflow. Both options allow you to customize autopep8’s behavior for specific lines in your code.

2023-11-23