Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Custom importer and errors
#1
Question 
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

import sys
from importlib.machinery import ModuleSpec
from pathlib import Path

Loader = type(__spec__.loader)

class IdeHelper:
    @classmethod
    def find_spec(cls, name, path, target=None):
        for dirname in sys.path:
            dirobj = Path(dirname)
            if dirobj.name == name:
                break
        else:
            return None
        origin = str(dirobj.joinpath('__init__.py').absolute())
        ret = ModuleSpec(name, Loader(name, origin), origin=origin)
        return ret

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
Error:
ModuleNotFoundError: No module named 'top.child1'; 'top' is not a package
whereas with 'from top import child1' the error changes to
Error:
ImportError: cannot import name 'child1' from 'top' (unknown location)
How can I make this work?

Best wishes,
Fabiano
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,893 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