Namespace modules - are they legal?

In the page https://packaging.python.org/en/latest/guides/packaging-namespace-packages/ one can find detailed explanation how to add Python packages to the namespaces. But what about adding Python modules to the namespaces?

I would like to say, that technically it is possible. You just need to slightly modify pyproject.toml - add there the section:

[tool.setuptools]
    py-modules = ["<namespace>.<module name>"]

and use usual command python -m bulld -w. Pip properly installs created whl-file.

On the other hand this functionality looks undocumented. I couldn’t find a single example on Google. It may also be unsupported and untested, so I would like to know the developers’ point of view.

Thank you in advance.


Andrew

Python sees very little difference between packages and modules, in fact, using the terms with the distinction you are making here (folders vs single files) is non-standard and can lead to confusion.

It’s potentially slightly unusual since normally namespace packages are for larger projects where each component is already too complex for a single file, but there is nothing “illegal” about it.

1 Like

It’s perfectly legal. Any time you have a namespaced foo.bar.baz, there is necessarily a foo package involved. It could be that bar is a module and baz is something defined in there; or it could be that bar is a package and baz is a module in that package. But that isn’t a real distinction. A package is a module - Python represents it with the same type of object, not even a subtype. And a module within a package is just an attribute of that package in the exact same way that a class might be an attribute of that module.

But writing your pyproject.toml this way is pointless. the reason tool.setuptools.py-modules is a thing is so that Setuptools can be instructed to put either files or folders into the wheel (or sdist). But if you really want a particular module to be namespaced, it’s far easier to just have a folder in your project which contains the .py file. The resulting wheel should, if I’m thinking straight, be identical anyway.

Although I guess this could be a way to include only part of a package in a given distribution, while using pyproject.toml rather than asking Setuptools to process a MANIFEST.in. But really: a single module within a namespace (one deep) is really the same thing as a package that contains a module. Python creates an actual module object, and stores it in sys.modules, to represent the folder - whether or not it has an __init__.py.

1 Like

I would say, there are not strict naming convetions in Python. So you can add also submodules and other featureds to a namespace.