You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地Python包导入异常:无法通过import mypackage调用tools模块

本地Python包导入问题解决

包结构

本地Python包目录结构如下:

D:.
|   .gitignore
|   LICENSE
|   pyproject.toml
|   README.md
|   requirements.txt
+---.venv
|   |   ...            
+---mypackage
|   |   __init__.py
|   +---moduleA
|   |   |   module_a_src.py
|   |   |   module_a_helpers.py          
|   +---tools
|   |       tools.py 
\---tests
  • mypackage/__init__.py 文件为空
  • tools.py 内容:
def working(string):
    print(string)

print("here i am")

已通过 pip install -e . 将包以可编辑模式安装到本地venv环境,当前可正常执行以下命令:

$ py -c "from mypackage.tools import tools; tools.working('foo')"
here i am
foo
(.venv)

需求与问题

希望通过 py -c "import mypackage; tools.working('foo')" 调用功能,但执行后报错:

$ py -c "import mypackage; tools.working('foo')"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'tools' is not defined
here i am
(.venv)

已尝试在 tools 文件夹添加空 __init__.py,问题仍未解决。当前 pyproject.toml 内容:

[tool.setuptools]
include-package-data = true

[tool.setuptools.packages.find]
where = [".", "mypackage"]

解决方案

1. 修正子包配置(已完成)

确保 mypackage/tools 是合法Python子包,该目录下已添加空 __init__.py,这一步你已经完成。

2. 调整顶层包的导入逻辑

修改 mypackage/__init__.py,根据你的调用需求选择以下导入方式:

方式一:直接将working函数暴露到顶层包

from .tools.tools import working

调用命令改为:

py -c "import mypackage; mypackage.working('foo')"

方式二:将tools.py模块导入到顶层包命名空间

from .tools import tools

调用命令改为(需通过包名访问):

py -c "import mypackage; mypackage.tools.working('foo')"

方式三:将tools子包导入到顶层包

from . import tools

调用命令改为:

py -c "import mypackage; mypackage.tools.tools.working('foo')"

3. 优化pyproject.toml配置

建议将packages.find.where修改为仅包含包目录,避免识别根目录为包:

[tool.setuptools.packages.find]
where = ["mypackage"]

问题原因说明

报错NameError: name 'tools' is not defined是因为:

  • 仅import mypackage时,tools模块并未被导入到全局命名空间
  • 同时未在顶层包的__init__.py中把tools相关内容暴露到包的顶层,导致无法直接访问

内容的提问来源于stack exchange,提问作者a11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:30:22