Is there a way to import a python package from another python package, as if it was part of the same code?

五迷三道 提交于 2020-01-16 14:01:47

问题


Let's say that we have python packages package_a and package_b. As a user, I want to be able to say:

from package_a.package_b import some_functionality

My question is: is there a way to support this without literally copy-pasting the code of package_b to package_a?

EDIT 1:

To clarify, I have shadow naming (my python package is named the same way as my folder), and I am wondering if there was a way to make the python package available somewhere else.

And yes, I'm looking into ways how to rename the package/folder in a way it still makes sense in the domain.


回答1:


This is an abuse of Python's module system, and I would urge you to reconsider this design, but if you really must, you can do it by messing with sys.modules:

In package_a/__init__.py:

import sys
import package_b

sys.modules[__name__ + '.package_b'] = package_b

You can see something like this in the standard lib, os.path is either thentpath or posixpath module depending on platform, neither of which is actually part of os (it couldn't be, os is a module, not a package).

https://github.com/python/cpython/blob/master/Lib/os.py

sys.modules['os.path'] = path



回答2:


With setuptools you can do something like this:

Project
├── setup.py
└── src
    ├── package_a
    │   └── __init__.py
    └── package_b
        └── __init__.py

setup.py

#!/usr/bin/env python3

import setuptools

setuptools.setup(
    name='Project',
    version='0.0.7',
    packages=[
        'package_a',
        'package_b',
        'package_a.package_b',
    ],
    package_dir={
        'package_a': 'src/package_a',
        'package_b': 'src/package_b',
        'package_a.package_b': 'src/package_b',
    },
)

This will effectively install two copies of package_b, one as a top level package and another one as a sub-package of package_a. Which could be a problem since if for example you have a global variables in package_b then it won't have the same value as the same global variable in package_a.package_b. But it might as well be a positive side effect, depending on the use cases.



来源:https://stackoverflow.com/questions/58595759/is-there-a-way-to-import-a-python-package-from-another-python-package-as-if-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!