16

With a project structure like this:

├─main.py
└─src
    ├─dep1.py
    └─dep2.py

where the contents of each file is as follows:

main.py: import src.dep1 as firstdep; print("Total success")

dep1.py: import dep2 as seconddeb; print("success 1/3")

dep2.py: print("success 2/3")

Is the best way to do this creating an __init__.py file in src and importing src.dep2 in dep1.py? or is this a bad idea?

you are viewing a single comment's thread
view the rest of the comments
[-] rtxn@lemmy.world 14 points 3 weeks ago* (last edited 3 weeks ago)

If you have to import a directory structure, you should make each directory a module by creating an __init__.py file in them, and use relative import statements. I usually have one main.py as the entry point, which imports a lib module that contains all of the program logic.

├── lib
│   ├── __init__.py
│   ├── module_content.py
│   └── submodule
│       ├── __init__.py
│       └── submodule_content.py
└── main.py

You can import the lib directory as a module:

main.py:

from lib import some_fn

Within any module, though, you should use relative import statements to import from files and submodules, and regular import statements to import packages from the system or the venv:

lib/__init__.py:

from .module_content import some_fn # import from a file
from .submodule import some_other_fn # import from a submodule directory
from os.path import join # import from an installed package

Items that you define in __init__.py or import into it will be available to import from the module: from .submodule import some_fn. Otherwise, you can import an item from a file by specifying the full path: from .submodule.submodule_content import some_fn.

You can also import an item from a parent package using the .. prefix: from ..some_other_submodule import some_fn.

[-] Limitless_screaming@kbin.earth 3 points 3 weeks ago

Items that you define in __init__.py or import into it will be available to import from the module: from .submodule import some_fn

That will be very useful. Thanks for your quick reply!

this post was submitted on 06 Nov 2025
16 points (100.0% liked)

Python

7589 readers
1 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

📅 Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
💓 Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 2 years ago
MODERATORS