In our projects instead of using relative imports, we usually create the code as python packages and install them with pip install -e .
This is nice and prevents from issues with import errors on different machines/IDEs.
However, for bigger project with a deeper structure this however means quite long import statements, which is where problem with black starts. E.G the following (dummy) example import
from root.machine_vision.hardware_layer.cameras.some_camera_brand. \
camera_access_class import CameraAccessClass
would be changed by black into
from root.machine_vision.hardware_layer.cameras.some_camera_brand.camera_access_class import (
CameraAccessClass
)
Which would cause issues with the max. line length.
So far I have only found this post, which suggests to turn black off for the block in question with # fmt: off
and # fmt: on
. I'm wondering if it is possible to tell black to allow backslashes in these kind of imports.
On the other hand, is there maybe another way to handle such long imports? For example some way to do "part imports", which would look something like
import root.machine_vision.hardware_layer as hwl
from hwl.cameras.some_camera_brand.camera_access_class import CameraAccessClass
So far I have not found a satisfactory solution...
Despite the surface similarities, there is a distinct difference between a fully qualified module name like root.machine_vesion.hardware_layer.cameras
and an expression like hwl.cameras
. hwl
is a variable that refers to a particular package, not the name of that package, and whether that package has an attribute named cameras
is determined by the package itself.
Assuming the package root.machine_version.hardware_layers
does exposes cameras
as an attribute, (and each lower package exposes the necessary module as an attribute as well) you could write
import root.machine_vision.hardware_layer as hwl
CameraAccessClass = hwl.cameras.some_camera_brand.camera_access_class.CameraAccessClass
The following
from hwl.cameras.some_camera_brand.camera_access_class import CameraAccessClass
would not work because the import
statement requires a module name, not an expression that evaluates to a module
object.