Poetry构建的自定义Python包导入失败,求排查问题
问题:使用Poetry创建的Python包无法在其他项目中导入
我尝试用Poetry创建Python包并上传到Docker运行的DevPi,之后在另一个项目中安装该包,但导入后项目无法识别它,安装过程无异常。
库项目
pyproject.toml内容
[tool.poetry] name = "python-lib-example" version = "0.5.0" description = "" authors = ["xxx"] readme = "README.md" packages = [{include = "python_lib_example"}] [tool.poetry.dependencies] python = "^3.12" [tool.poetry.group.dev.dependencies] devpi-client = "^7.1.0" [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api
测试类代码
class PersonInfo: def __init__(self, name, age): self.name = name self.age = age def get_name(self): return self.name def get_age(self): return self.age def get_info(self): return f'{self.name} is {self.age} years old' def __str__(self): return self.get_info()
项目结构
根目录下包含:
python_lib_example文件夹(内含空的__init__.py和上述测试类文件)pyproject.tomlREADME.md
操作步骤
构建包并上传至Docker运行的DevPi
目标项目
pyproject.toml内容
[tool.poetry] name = "python-app-example" version = "0.0.1" description = "" authors = ["xxx"] readme = "README.md" package-mode = false [tool.poetry.dependencies] python = "^3.12" python-lib-example = {version = "^0.5.0", source = "mjana"} [[tool.poetry.source]] name = "mjana" url = "http://localhost:3141/mjana/mjana/+simple" priority = "supplemental" [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api
导入尝试
from python_lib_example import PersonInfo
问题排查与解决方案
修复pyproject.toml语法错误
两个项目的[build-system]部分中,build-backend的值都缺少闭合双引号,这会导致包构建不完整:
修正后代码:build-backend = "poetry.core.masonry.api"暴露库中的类到包顶层
库项目的python_lib_example/__init__.py为空,导致PersonInfo类无法被外部直接导入。需要在__init__.py中添加导出语句(注意替换为测试类实际的文件名):from .person_info import PersonInfo重新构建并上传包
- 修正库项目的配置后,执行
poetry build确保无报错,生成完整的wheel/sdist包。 - 重新上传到DevPi,在目标项目中执行
poetry update python-lib-example,确保安装的是修正后的版本。
- 修正库项目的配置后,执行
检查目标项目的package-mode配置
目标项目中package-mode = false可能干扰Poetry对依赖的处理,建议移除该配置(默认值true更适合应用类项目)。
内容的提问来源于stack exchange,提问作者Michal
相关产品推荐
相关产品推荐

