Init 导入但未使用的 pythonpep8类

我正在使用 pythonFlake8库在 python 中执行 PEP8检查。我在我的子模块的 __init__.py文件中有一个 import 语句,它看起来像这样:

from .my_class import MyClass

我在 init 文件中使用这一行的原因是,我可以从子模块导入 MyClass 作为 from somemodule import MyClass,而不必编写 from somemodule.my_class import MyClass

我想知道是否有可能维护这个功能,同时纠正 PEP8违规?

27351 次浏览

This is not actually a PEP8 violation. I simply do this:

from .my_class import MyClass  # noqa

Edit: Another possibility is to use __all__. In that case, flake8 understands what is going on:

from .my_class import MyClass


__all__ = ['MyClass',]

According to PEP 8, you should include MyClass in __all__, which will also fix the imported-but-not-used issue:

To better support introspection, modules should explicitly declare the names in their public API using the __all__ attribute.

According to flake8's documention, you can in-line ignore this specific warning with:

from .my_class import MyClass  # noqa: F401

For reference, here are flake8's error codes.