Python 3导入优先级与__init__.py:自定义test包遮蔽内置包报错
ImportError: cannot import name 'test_request_billing_id' When Importing Custom test Module Oh, I’ve run into this exact issue before! Let’s break down what’s happening here and how to fix it.
First, let’s recap your project structure (note the typo in requets_billing_id.py—might want to fix that too, but that’s not the root problem here):
├── test │ └── test_request_billing_id.py └── requets_billing_id.py
Why the Import Error Happens
When you run from test import test_request_billing_id in the Python Shell, Python’s module lookup prioritizes standard library packages over local directories. Since test is the name of a built-in Python package, it’s loading that instead of your custom test folder. Unsurprisingly, the built-in test package doesn’t have a test_request_billing_id module, hence the ImportError.
How to Verify This
To confirm this is the issue, run these two lines in your Python Shell:
import test print(test.__file__)
If the output points to a file in your Python standard library path (like /usr/lib/python3.10/test/__init__.py or similar), that’s proof Python is grabbing the built-in test package instead of your local directory.
The Fixes
1. Rename Your Directory (Recommended)
The cleanest and most standard solution is to rename your custom test directory to tests—this is the de facto standard for test directories in Python projects and avoids conflicting with the built-in package. Your updated structure will look like this:
├── tests │ └── test_request_billing_id.py └── requets_billing_id.py
Now you can import successfully with:
from tests import test_request_billing_id
2. Force Python to Look for Local Modules First (Not Recommended)
If you absolutely can’t rename the directory right now, you can manually add your project directory to the start of Python’s module search path:
import sys sys.path.insert(0, './') from test import test_request_billing_id
This works, but it’s not ideal—it messes with Python’s default lookup order and could cause unexpected issues down the line. Stick with renaming to tests if you can.
内容的提问来源于stack exchange,提问作者James Lin

