Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Custom importer and errors
#6
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 '.' 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__.py
Now 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 child1
and
# top_child1/__init__.py
import top_child1_child2 as child2
This 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 »
Reply


Messages In This Thread
Custom importer and errors - by Fips - Apr-13-2024, 10:10 PM
RE: Custom importer and errors - by Pedroski55 - Apr-14-2024, 05:38 AM
RE: Custom importer and errors - by Fips - Apr-14-2024, 06:51 AM
RE: Custom importer and errors - by Pedroski55 - Apr-14-2024, 07:13 AM
RE: Custom importer and errors - by Fips - Apr-14-2024, 08:47 AM
RE: Custom importer and errors - by Gribouillis - Apr-14-2024, 08:58 AM
RE: Custom importer and errors - by Pedroski55 - Apr-14-2024, 02:34 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  informatio from importer to importee Skaperen 4 2,854 Nov-19-2018, 03:22 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020