112

I'm doing PEP8 checks in python using the python flake8 library. I have an import statement in an __init__.py file in one of my sub-modules which looks like this:

from .my_class import MyClass

The reason I have this line in the init file is so that I can import MyClass from the sub-module as from somemodule import MyClass instead of having to write from somemodule.my_class import MyClass.

I would like to know if it is possible to maintain this functionality while correcting the PEP8 violation?

Salvius
  • 1,193
  • 2
  • 8
  • 8

4 Answers4

174

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',]
René Fleschenberg
  • 2,418
  • 1
  • 15
  • 11
61

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.

Mihai Capotă
  • 2,271
  • 2
  • 32
  • 24
20

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.

Mike T
  • 41,085
  • 18
  • 152
  • 203
0

You can use flake8 per-file ignore: https://flake8.pycqa.org/en/latest/user/options.html#cmdoption-flake8-per-file-ignores

  • use command line option flake8 --per-file-ignores='__init__.py:F401

  • or add this to setup.cfg, tox.ini or .flake8 file:

    [flake8]
    per-file-ignores =
        # imported but unused
        __init__.py: F401
    
Messa
  • 24,321
  • 6
  • 68
  • 92