Search code examples
pythonimportmodulesubdirectory

Avoid adding file and folder names to a module's namespace


Is there a way to avoid adding file and folder names to a module's namespace? With the following structure:

├── pkg
│   ├── __init__.py
│   ├── folder
│   │   └── func2.py
│   └── func1.py

__init__.py:

from .func1 import a
from .folder.func2 import b

Then importing

>>> import pkg
>>> dir(pkg)

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__path__', '__spec__', 'a', 'b', 'folder', 'func1']

Is there a way to set up the project so folder and func1 don't appear in the module's namespace?


Solution

  • You can add the following to your __init__.py as per https://stackoverflow.com/a/32234323/16173463:

    del folder
    del func1
    

    Result:

    >>> import pkg
    >>> dir(pkg)
    ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'a', 'b']