[英]Allow statements before imports with Visual Studio Code and autopep8
I'm using Visual Studio Code with the Python plugin and autopep8 with:我将 Visual Studio Code 与 Python 插件和 autopep8 一起使用:
"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.但是当我保存时,Visual Studio Code/autopep8 将所有导入语句移动到代码之前,因此 Python 找不到我的本地包。
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?我如何告诉 Visual Studio Code/autopep8 在导入之前放置一个语句是可以的,或者是否有更正确的导入本地包的方法?
As a workaround, it looks like it's fine if you import in an if statement:作为一种解决方法,如果您在if语句中导入似乎没问题:
import sys
sys.path.insert(0, '/path/to/packages')
if 'localpackage' not in sys.modules:
import localpackage
Open settings打开设置
Search for autopep8.搜索 autopep8。 You should see the following results:
您应该会看到以下结果:
Click on "Edit in settings.json" under the first option单击第一个选项下的“在 settings.json 中编辑”
Add the following argument to the User Settings JSON file:将以下参数添加到用户设置 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)这告诉
autopep8
忽略错误 402,即:“模块级导入不在文件顶部”(这是 pep8中的错误列表)
You can use this same method to change any of the autopep8
settings.您可以使用相同的方法更改任何
autopep8
设置。 For example, if you only wanted to fix indentation, you can use "python.formatting.autopep8Args": ["--select", "E1"]
例如,如果你只想修复缩进,你可以使用
"python.formatting.autopep8Args": ["--select", "E1"]
The autopep8 readme has more information on the available options. autopep8 自述文件包含有关可用选项的更多信息。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.