Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pep8 class in init imported but not used

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?

like image 397
Salvius Avatar asked Jun 26 '15 17:06

Salvius


People also ask

What is __ all __ in Python?

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.

How do I order imports in Python?

Imports should be grouped in the following order: Standard library imports. Related third party imports. Local application/library specific imports.

How to name modules in Python?

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.

What do I put in an init file?

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.


3 Answers

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',]
like image 51
René Fleschenberg Avatar answered Oct 17 '22 11:10

René Fleschenberg


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.

like image 22
Mihai Capotă Avatar answered Oct 17 '22 09:10

Mihai Capotă


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.

like image 17
Mike T Avatar answered Oct 17 '22 11:10

Mike T