Apr-14-2024, 08:58 AM
I think all this is a terrible idea. In Python it is very important to distinguish the modules hierarchy from the OS folders hierarchy. These are really two different things and the idea of using folder names that contain dot characters
On your local machine, a simpler thing that you could do is use the
That being said, it is not a good idea to make assumptions about the trees of directories when you want to package and distribute your modules. If you want to separate modules, write modules that can be installed independently, so you could write a
'.'
can only confuse the import mechanism.On your local machine, a simpler thing that you could do is use the
__path__
attributes of packages to locate subpackages in another directory. For example suppose I have 3 directories top, child1, child2 all in the same folder, I can write# top/__init__.py from pathlib import Path __path__.append(str(Path(__file__).parent.parent)) def greet(module): print(f'Greetings from module {module.__name__}')and also
# child1/__init__.py from pathlib import Path __path__.append(str(Path(__file__).parent.parent))and
# child2/__init__.pyNow packages are properly imported
>>> from top import greet >>> from top.child1 import child2 >>> greet(child2) Greetings from module top.child1.child2 >>>Using this system, one can play with trees of directories to locate subpackages elsewhere in the file system.
That being said, it is not a good idea to make assumptions about the trees of directories when you want to package and distribute your modules. If you want to separate modules, write modules that can be installed independently, so you could write a
top
package, a top_child1
package and a top_child1_child2
package, each pip-intallable, and then you can write if you want# top/__init__.py import top_child1 as child1and
# top_child1/__init__.py import top_child1_child2 as child2This is much more robust, but there are some differences, for example with this setup,
top.child1
will not be considered by Python as a subpackage of top
, so specific code like pkgutil that explore the subpackages will behave differently.
« We can solve any problem by introducing an extra level of indirection »