How to organize multiple python files into a single module without it behaving like a package?

You can sort of do it, but it’s not really a good idea and you’re fighting against the way Python modules/packages are supposed to work. By importing appropriate names in __init__.py you can make them accessible in the package namespace. By deleting module names you can make them inaccessible. (For why you need to delete them, see this question). So you can get close to what you want with something like this (in __init__.py):

from another_class import doit
from another_class import dataholder
from descriptive_name import getSomeStuff
from descriptive_name import hold_more_data
del another_class, descriptive_name
__all__ = ['doit', 'dataholder', 'getSomeStuff', 'hold_more_data']

However, this will break subsequent attempts to import package.another_class. In general, you can’t import anything from a package.module without making package.module accessible as an importable reference to that module (although with the __all__ you can control from package import *).

More generally, by splitting up your code by class/function you are working against the Python package/module system. A Python module should generally contain stuff you want to import as a unit. It’s not uncommon to import submodule components directly in the top-level package namespace for convenience, but the reverse — trying to hide the submodules and allow access to their contents only through the top-level package namespace — is going to lead to problems. In addition, there is nothing to be gained by trying to “cleanse” the package namespace of the modules. Those modules are supposed to be in the package namespace; that’s where they belong.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)