Sibling package imports
Use relative imports with leading dots to import from sibling packages, given your folder structure supports it:
Or adjust sys.path before importing to include the parent directory:
Remember not to run your script as __main__
—it's a party pooper for relative imports.
Structuring your project: Setup script and package layout
Good structure is the key. Follow these practices:
- Create setup.py: Use
setuptools.setup()
to define your package structure—It's like a fancy VIP invitation for packages to join your project.
-
Organize as a folder with setup.py: Each package is a room at your party, an
__init__.py
file tells Python it's a room worth visiting. -
Install in editable state: Use
pip install -e <myproject_folder>
—like putting your project on the VIP list to update without invites (re-installing). -
Use virtual environments: They're like separate party venues for your projects
venv
, ensuring no party (project) crashers (conflicts).
Running scripts without headaches
How to avoid "Address not found" errors for your scripts' import statements:
- Run scripts with
python -m
, treating directories as packages.
- Use
pytest
for testing—It's like a bouncer, managing who's on yoursys.path
, no need for hacks. - Have a setup.cfg as your project's guest list—It keeps metadata, making package installation smoother for others.
Import protocols: Making correct references
Here's the etiquette for importing within your package:
- Prefer relative imports: They make your package a close-knit party crowd, easier to follow who's with who.
- Use PEP guidance for better compatibility across Python versions.
- Avoid
sys.path.insert
hacks: They're party crashers, causing maintainability issues.
Handling imports in large projects
The import party can spiral if not well managed. Below are best practices:
- Simplify project structure: Too many rooms at your party? Redesign it!
- Place tests within packages: They're the party characters everyone wants to know—they should be easy to find.
- Remove unnecessary
__init__.py
files: Python 3.3+ are cool guests who recognize when a party (implicit namespace package) is going on without an explicit invite (__init__.py
file).
Keeping your project future-proof
Finally, keep your project nimble and ready for the future:
- Ensure your directory structure supports package imports when writing scripts.
- Conduct regular refactoring to simplify import paths.
- Keep updating your practices with Python's latest standards
Was this article helpful?