首页 > 解决方案 > In a module, how can I include submodules for environments where they may not be installed, without modifying sys.path?

问题描述

I am writing a Python module, call it module A. Module A depends on module B which depends on modules C and D, none of which are standard libraries, and none of which are my own. Module A is for use in Python environments where it is either known for certain, or else highly unlikely, that modules B, C and D are installed out of the box, such as Sublime Text, Pythonista, or some other tool that has its own Python environment.

Now what if I wanted to incorporate module A along with modules B - D, into a package for a (non-developer) end user, let's call it Package 1, for use in one environment (say Sublime Text), and also another, Package 2, for another environment (say for Pythonista). I want to bundle Module A, along with its dependencies, Modules B, C and D, into both packages, such that the import paths in all four modules can remain the same in both, while preserving any relative imports that may exist inside of Modules B, C and D?

This all might be for many reasons, but mine are:

Now suppose, in addition, that the developer of one such intended environment (Sublime Text) asks that this be done without modifying sys.path...

For instance, I have the following folder structure:

+ Package 1
  + __init__.py
  + (etc.)
  |
  +-- module_a
  |   + __init__.py
  |   + code.py
  |
  +-- module_b
  |   + __init__.py
  |   + ...
  +-- module_c
  |   + __init__.py
  |   + ...
  +-- module_d
      ...

Then in Module A, I can write:

from ..module_b import something

But since Module B's own path is not in the import path, if Module B needs a relative import from its own folder, it cannot find it unless I go into module_b and change:

from module_b.something_else import SomethingElse

to:

from .something_else import SomethingElse

... and so on. This seems like a mess, and seems to be the case no matter how I build the Package folder. I would like to know if there is a way to do this while adhering to the request not to modify sys.path.

标签: pythonsublimetext3

解决方案


推荐阅读