'Import independent Python package as if importing subpackage

Problem

I have a fairly large package that is structured as follows:

package
  subpackage1
    __init__.py
    subsubpackages1
    modules1.py
    ...
  subpackage2
    __init__.py
    subsubpackages2
    modules2.py
    ...
  subpackage3
    ...

Now I'd like to split off subpackage2 into another repository as an independent package (let's call it new_package). However, I still need backwards compatibility with present code which imports as a subpackage, e.g.:

import package.subpackage2.modules2
from package.subpackage2 import modules2
import package.subpackage2.subsubpackages2.<and_so_on>

should still work, without the need to change all existing code to

import new_package.modules2
from new_package import modules2
import new_package.subsubpackages2.<and_so_on>

Possible solutions

The straightforward way would be to create a new subpackage2 in place, which would import from new_package, but that would not work for full import statements as they operate on the full package/module names.

I also thought about editing the sys.modules dict after importing new_package, but to my understanding each individual module would have to be accounted for, which would require all submodules of new_package to be imported at that point (which would also be undesirable).

Question

Since I'm not very familiar with the inner workings of importing packages: Is there any best-practice (or generally better) way of how to accomplish this? Would the procedure outlined above work reliably in principle?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source