Let's say I am writing a python module module.py. Which provides functionalities for other parts of my code. Of course, the module has to import other modules. A simple example:
import abc as _abc
import typing as _typing
class BaseFunctionality(_abc.ABC):
def get_sequence(self) -> _typing.Sequence[float]:
return (1, 2.5, 5.6)
def get_nested_sequence(self) -> _typing.Sequence[_typing.Sequence[float]]:
return (1, 2.5, 5.6)
As you can see, I am using the "import as underscore" way of importing the modules. I think this is a good way of doing so because:
- It does not clutter up the module namespace.
- The modules
abcandtypingare visible from outside ofmoduleas_abcand_typingwhere the underscore implies "please don't touch this". They are not part of the module functionality itself.
However, this can be tedious. See for example the definition of getsequence(self). The return type annotation is quite long. And this might get even longer when nesting types. Simply writing def getsequence(self) -> Sequence[float]: would be much nicer and more readable, but then I would have to from typing import Sequence which adds Sequence to the module's namespace. I guess as a compromise I could also from typing import Sequence as _Sequence and continue using the annotation with the underscore.
All of this seems rather unpractical. Is there a way to unify the benefits of this way of importing with the benefit of shorter annotations? Of course, in this example I used annotations, but of course, this generalizes to all accesses to the modules.
import a as _a-imports, then it is not a "problem" directly I am trying to solve. The basic idea is that from outside the module you should only access the members that do not start with "_". These would be the internal members from the imported modules. Of course, no one ultimately stops you from accessing them anyway, but this is the cleaner approach.