如何打包一个 python 模块,该模块在该包中导入另一个模块

How to package a python module that imports another module within that package

我正在创建一个 python 3.7.2 包,然后将其安装在不同的位置,在 virtualenv 中以在应用程序中使用。我的包有多个模块,它们之间存在依赖关系(导入)。我不知道如何让包正确加载,以便我可以使用包中的依赖模块。

包目录

root
\- foo # my package
   \- __init__.py # empty or with from .helper_class import HelperClass
   \- helper_class.py
   \- my_class.py # imports helper_class
   setup.py

应用目录

app
\- main.py # from foo.my_class import MyClass
\- venv

my_class不导入helper_class时,我可以打包,安装和运行 main.py就好了。当我在 my_class 中导入 helper_class 时,我得到 ModuleNotFoundError.

$ python main.py
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from foo.my_class import MyClass
  File "/Users/XXXXXX/tmp/foo/my_class.py", line 1, in <module>
    from helper_class import HelperClass
ModuleNotFoundError: No module named 'helper_class'

我尝试了一个空的 __init__.py,并且还添加了 from .helper_class import HelperClass__init__.py。我已经在各处的引用中添加了 .s,但没有爱。

一定有什么非常明显的东西是我遗漏的。

app/main.py


o = MyClass()
print(o.get_att())

foo/my_class.py

from helper_class import HelperClass

class MyClass():
    def __init__(self):
        self.att = 123
    def get_att(self):
        return self.att

foo/helper_class.py

class HelperClass():
    def __init__(self):
        pass

Setup.py 下面(摘自 https://github.com/navdeep-G/setup.py

    name=NAME,
    version=about['__version__'],
    description=DESCRIPTION,
    long_description=long_description,
    long_description_content_type='text/markdown',
    author=AUTHOR,
    author_email=EMAIL,
    python_requires=REQUIRES_PYTHON,
    url=URL,
    packages=['foo', ],
    # packages=find_packages(exclude=["tests", "*.tests", "*.tests.*", "tests.*"]),
    # If your package is a single module, use this instead of 'packages':
    # py_modules=['mypackage'],

    # entry_points={
    #     'console_scripts': ['mycli=mymodule:cli'],
    # },
    install_requires=REQUIRED,
    extras_require=EXTRAS,
    include_package_data=True,
    license='MIT',
    classifiers=[
        # Trove classifiers
        # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: Implementation :: CPython',
        'Programming Language :: Python :: Implementation :: PyPy'
    ],
    # $ setup.py publish support.
    # cmdclass={
    #     'upload': UploadCommand,
    # },
)

请尝试按以下方式导入...

from foo.helper_class import HelperClass