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?
Python __all__ It's a list of public objects of that module, as interpreted by import * . It overrides the default of hiding everything that begins with an underscore.
Imports should be grouped in the following order: Standard library imports. Related third party imports. Local application/library specific imports.
Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
The most minimal thing to do is to leave the __init__.py file totally empty. Moving slightly away from this, while still keeping things simple, you can use an __init__.py only for determining import order. Another step up on the spectrum, you can use the __init__.py file to define the API of the package.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With