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

Python 2/3中无法对包内types.py文件执行doctest的问题求助

Why doctest fails to detect tests in foo/types.py but works with foo/types2.py

The Root Cause

The core issue here is that types is a built-in Python module—Python ships with its own types module in the standard library. When you run python -m doctest -v foo/types.py, doctest tries to import the module under the name types, but Python prioritizes loading the built-in types module over your custom foo/types.py. That’s why you see the message "1 items had no tests: types"—doctest is looking at the wrong module entirely!

When you rename the file to types2.py, there’s no conflict with a built-in module name, so doctest correctly imports your custom file and picks up the doctests inside the x() function.

Solutions to Fix This

1. Rename Your File (Simplest & Recommended)

Just choose a filename that doesn’t clash with Python’s built-in modules. For example:

mv foo/types.py foo/custom_types.py
python -m doctest -v foo/custom_types.py

This eliminates the name conflict entirely and works without any extra steps.

2. Use the Full Module Path (If You Must Keep the Name)

If you need to retain types.py, first make sure your foo directory is a proper Python package (add an empty __init__.py file if it doesn’t exist). Then run doctest using the full module reference:

# Create __init__.py to mark foo as a package
touch foo/__init__.py
# Run doctest on your foo.types module explicitly
python -m doctest -v foo.types

This tells Python to import your custom foo.types module instead of the built-in one.

3. Run Doctest From Inside the Package Directory

Change into the foo directory and run doctest directly on the file—this avoids the module name conflict in the import path:

cd foo
python -m doctest -v types.py

Verification

After applying any of these fixes, you’ll see doctest correctly detect and run your test case for x(), just like it did with types2.py.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:03:09