上传Python包至PyPI后无法访问模块问题求助
Hey there! Let's break down why you're seeing those AttributeError messages and fix this step by step—this is a super common gotcha when creating your first Python package, so don't worry, we'll get it sorted.
1. First, Check Your Package Directory Structure
Make sure your package has the correct hierarchy. It should look something like this:
testeroozz/ __init__.py sum_module.py
Inside sum_module.py, confirm your Summation class and great_summation method are defined properly. If your file is nested in a subfolder or named incorrectly, Python won't be able to locate it.
2. Update Your __init__.py File
By default, when you import testeroozz, Python only loads the code in __init__.py—it doesn't automatically import submodules like sum_module. To expose your class, method, and submodule to the top-level package, add these lines to testeroozz/__init__.py:
# Expose the submodule itself so users can access testeroozz.sum_module from . import sum_module # Expose the class and method directly at the package level from .sum_module import Summation, great_summation
This makes those items visible when someone runs dir(testeroozz), and lets users call testeroozz.Summation() or testeroozz.great_summation() directly.
3. Verify Your Build Configuration (setup.py/pyproject.toml)
Double-check that your build file includes all necessary files. If you're using setuptools, make sure you're using find_packages() in your setup.py to automatically detect all submodules:
from setuptools import setup, find_packages setup( name="testeroozz", version="0.2", packages=find_packages(), # This will include testeroozz and sum_module # ... other configs like author, description, dependencies, etc. )
If you're using pyproject.toml, ensure your [tool.setuptools] section doesn't accidentally exclude sum_module.py.
4. Test Locally Before Re-Uploading to PyPI
Don't waste time re-uploading to PyPI to test changes! Install your package locally in editable mode first:
pip install -e .
Then open a Python shell and test the imports:
import testeroozz dir(testeroozz) # Should now show sum_module, Summation, great_summation testeroozz.great_summation(1, 2) # Test the method works
This lets you iterate quickly without waiting for PyPI updates.
5. Clear Old Package Caches
If you've installed previous versions of your package, pip might be using a cached outdated version. Uninstall it completely first:
pip uninstall -y testeroozz
Then install the updated version (either locally or from PyPI once you re-upload the fixed package).
Once you make these changes, rebuild your package, upload the new version to PyPI, and the imports should work as expected!
内容的提问来源于stack exchange,提问作者ilmoi

