Python PEP8 –?import not at the top of file with sys.path

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36827962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:24:31  来源:igfitidea点击:

PEP8 –?import not at top of file with sys.path

pythonpython-3.xpep8

提问by Luke Taylor

Problem

问题

PEP8 has a rule about putting imports at the top of a file:

PEP8 有一个关于将导入放在文件顶部的规则:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

导入总是放在文件的顶部,就在任何模块注释和文档字符串之后,以及模块全局变量和常量之前。

However, in certain cases, I might want to do something like:

但是,在某些情况下,我可能想要执行以下操作:

import sys
sys.path.insert("..", 0)

import my_module

In this case, the pep8command line utility flags my code:

在这种情况下,pep8命令行实用程序会标记我的代码:

E402 module level import not at top of file

E402 模块级导入不在文件顶部

What is the best way to achieve PEP8 compliance with sys.pathmodifications?

通过sys.path修改实现 PEP8 合规性的最佳方法是什么?

Why

为什么

I have this code because I'm following the project structuregiven in The Hitchhiker's Guide to Python.

我有这个代码是因为我遵循The Hitchhiker's Guide to Python 中给出的项目结构

That guide suggests that I have a my_modulefolder, separate from a testsfolder, both of which are in the same directory. If I want to access my_modulefrom tests, I think I need to add ..to the sys.path

该指南建议我有一个my_module文件夹,与文件夹分开tests,两者都在同一目录中。如果我想访问my_modulefrom tests,我想我需要添加..sys.path

采纳答案by Roland Smith

Often I have multiple files with tests in a subdirectory foo/testsof my project, while the modules I'm testing are in foo/src. To run the tests from foo/testswithout import errors I create a file foo/tests/pathmagic.pythat looks like this;

通常,我在foo/tests项目的子目录中有多个带有测试的文件,而我正在测试的模块在foo/src. 为了在foo/tests没有导入错误的情况下运行测试,我创建了一个如下所示的文件foo/tests/pathmagic.py

"""Path hack to make tests work."""

import os
import sys

bp = os.path.dirname(os.path.realpath('.')).split(os.sep)
modpath = os.sep.join(bp + ['src'])
sys.path.insert(0, modpath)

In every test file, I then use

在每个测试文件中,我然后使用

import pathmagic  # noqa

as the first import. The "noqa" comment prevents pycodestyle/pep8from complaining about an unused import.

作为第一个导入。"noqa" 注释可防止pycodestyle/pep8抱怨未使用的导入。

回答by astorga

If there are just a few imports, you can just ignore PEP8 on those importlines:

如果只有几个导入,您可以忽略这些import行上的 PEP8 :

import sys
sys.path.insert("..", 0)
import my_module  # noqa: E402

回答by Peuchele

There is another workaround.

还有另一种解决方法。

import sys
... all your other imports...

sys.path.insert("..", 0)
try:
    import my_module
except:
    raise

回答by Daniel Lee

Did you already try the following:

您是否已经尝试过以下操作:

import sys
from importlib import import_module

sys.path.insert("..", 0)

# import module
my_mod = import_module('my_module')

# get method or function from my_mod
my_method = getattr(my_mod , 'my_method')

回答by itsadok

I've just struggled with a similar question, and I think I found a slightly nicer solution than the accepted answer.

我刚刚在一个类似的问题上挣扎,我想我找到了一个比接受的答案更好的解决方案。

Create a pathmagicmodule that does the actual sys.path manipulation, but make the change within a context manager:

创建一个pathmagic执行实际 sys.path 操作的模块,但在上下文管理器中进行更改:

"""Path hack to make tests work."""

import os
import sys

class context:
    def __enter__(self):
        bp = os.path.dirname(os.path.realpath('.')).split(os.sep)
        modpath = os.sep.join(bp + ['src'])
        sys.path.insert(0, modpath)

    def __exit__(self, *args):
        pass

Then, in your test files (or wherever you need this), you do:

然后,在您的测试文件(或您需要的任何地方)中,您可以:

import pathmagic

with pathmagic.context():
    import my_module
    # ...

This way you don't get any complaints from flake8/pycodestyle, you don't need special comments, and the structure seems to make sense.

这样你就不会收到来自 flake8/pycodestyle 的任何抱怨,你不需要特别的注释,而且结构似乎是有道理的。

For extra neatness, consider actually reverting the path in the __exit__block, though this may cause problems with lazy imports (if you put the module code outside of the context), so maybe not worth the trouble.

为了更加整洁,请考虑实际恢复__exit__块中的路径,尽管这可能会导致延迟导入出现问题(如果您将模块代码放在上下文之外),因此可能不值得麻烦。



EDIT: Just saw a much simpler trick in an answer to a different question: add assert pathmagicunder your imports to avoid the noqacomment.

编辑:刚刚在另一个问题答案中看到了一个更简单的技巧:assert pathmagic在您的导入下添加以避免noqa评论。

回答by Pierre Barre

To comply with the pep8, you should include your project path to the python path in order to perform relative / absolute imports.

为了符合 pep8,您应该将项目路径包含到 python 路径中,以便执行相对/绝对导入。

To do so, you can have a look at this answer: Permanently add a directory to PYTHONPATH

为此,您可以查看此答案:将目录永久添加到 PYTHONPATH