Python包开发疑问:自定义代码文件应放置在哪个目录?
Question:
I've created an empty Python package with only the basic structure from the Python packaging tutorial:
/example_pkg /example_pkg __init__.py setup.py LICENSE README.md
Should I put my custom code files in the root directory, or somewhere else?
Answer:
Great question! Your custom code files belong in the inner example_pkg directory—right alongside that __init__.py file. Here's why:
- That inner directory is your package's actual namespace. When someone installs your package, Python looks here for the code they can import (e.g.,
from example_pkg import your_custom_module). Placing code anywhere else won't make it part of the package's importable namespace. - For example, if you're building a data processing tool, you could add
data_processor.pydirectly inside the innerexample_pkg. If you have utility functions, createutils.pythere too. This keeps your code organized and follows standard Python packaging conventions. - The files in the root directory (
setup.py,LICENSE,README.md) are strictly for packaging configuration and metadata—they shouldn't contain your functional code. Sticking code here would break import paths and make your package behave unpredictably for end users.
A quick bonus tip: If your package grows to have multiple distinct sub-components, you can create subdirectories inside the inner example_pkg (like example_pkg/core or example_pkg/helpers). Just add an __init__.py file to each subdirectory (optional in Python 3.3+, but recommended for compatibility with older versions) to turn them into importable sub-packages.
内容的提问来源于stack exchange,提问作者whoff

