Python don't leak package in namespace

Viewed 20

I have a package layout like this:

\package
\package\__init__.py
\package\process
\package\process\__init__.py
\package\utils
\package\utils\__init__.py

Inside \package\process\__init__.py I need to import stuff from the utils subpackage, but i do not want to leak utils into the process subpackage namespace. That is, if i simply do from .. import utils in the process subpackage, then users can access utils through package.process.utils, i don't want that. So i tried:

from .. import utils
def function1(arg: utils.DeviceType):
    return utils.helper(arg)
del utils

but when i then later call function1, this crashes because name 'utils' is not defined. I guess that is due to the del statement. One way to prevent this leak would be to do the import only in the function body, but i need it in the main namespace as above because of the type annotation for the function argument. I now solved it like this:

from .. import utils
def function1(arg: utils.DeviceType):
    from .. import utils    # need to import again, previous top-level one was just for the type annotation, and needed to be deleted to not befoul this package's namespace
    return utils.helper(arg)
del utils

These seems ugly and not optimal, doing the import twice. Am i missing something? Is there another way to solve this? I could from .. import utils as _utils so its at least not at an obvious name and flagged as internal to the user, but wouldn't that still leak out?

0 Answers
Related