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

Python包开发疑问:自定义代码文件应放置在哪个目录?

Where to Place Custom Code Files in a Basic Python Package Structure?

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.py directly inside the inner example_pkg. If you have utility functions, create utils.py there 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:55:50