Arran Duff
Arran Duff

Reputation: 1474

Is it possible to make a module available as an import from another module?

Upvotes: 0

Views: 50

Answers (1)

ale-cci
ale-cci

Reputation: 153

The only way i know how to do it is by creating a custom import hook. Here is the PEP for more information.

If you need some help on how to implement one, i'll suggest you to take a look at the six module, here and here


Basically your calcs/__init__.py will become like this:

''' calcs/__init__.py '''
from .new_dir import new_file1, new_file2
import sys

__path__ = []
__package__ = __name__


class CalcsImporter:
    def __init__(self, exported_mods):
        self.exported_mods = {
            f'{__name__}.{key}': value for key, value in exported_mods.items()
        }

    def find_module(self, fullname, path=None):
        if fullname in self.exported_mods:
            return self

        return None


    def load_module(self, fullname):
        try:
            return sys.modules[fullname]
        except KeyError:
            pass

        try:
            mod = self.exported_mods[fullname]
        except KeyError:
            raise ImportError('Unable to load %r' % fullname)

        mod.__loader__ = self
        sys.modules[fullname] = mod
        return mod

_importer = CalcsImporter({
    'new_file1': new_file1,
    'new_file2': new_file2,
})
sys.meta_path.append(_importer)

and you should be able to do from calcs.new_file1 import foo

Upvotes: 1

Related Questions