Custom importer and errors
Fabiano Sidler
python at aliases.systohc.net
Sat Apr 13 14:49:15 EDT 2024
Hi folks!
I'd like to split my package tree into several IDE projects and build a
custom
importer to import
'top.child1.child2'
from the directory
<python-path-entry>/top.child1.child2/__init__.py
so basically replacing the dots with slashes and having the package content
lying directly in the project folder. I have come up with this:
=== usercustomize.py ===
1 import sys
2 from importlib.machinery import ModuleSpec
3 from pathlib import Path
4
5 Loader = type(__spec__.loader)
6
7 class IdeHelper:
8 @classmethod
9 def find_spec(cls, name, path, target=None):
10 for dirname in sys.path:
11 dirobj = Path(dirname)
12 if dirobj.name == name:
13 break
14 else:
15 return None
16 origin = str(dirobj.joinpath('__init__.py').absolute())
17 ret = ModuleSpec(name, Loader(name, origin), origin=origin)
18 return ret
19
20 sys.meta_path.append(IdeHelper)
which I'm on the right direction with. Unfortunately, I'm getting errors
while
importing a subpackage. With 'import top.child1' the error is
ModuleNotFoundError: No module named 'top.child1'; 'top' is not a
package
whereas with 'from top import child1' the error changes to
ImportError: cannot import name 'child1' from 'top' (unknown location)
How can I make this work?
Best wishes,
Fabiano
More information about the Python-list
mailing list