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

Python

7662 readers
10 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
 

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
[–] tunetardis@piefed.ca 3 points 2 months ago (1 children)

As others have mentioned, I would add a src/__init__.py file to turn src into a package.

Then, inside dep1.py, you can do a relative import with:

from . import dep2  

I'm not sure why you're using as to make the module name longer? Usually, if I use it at all, I use it make things shorter. Anyway, once you've imported dep2, you can call dep2.some_fn(). You could also go:

from .dep2 import some_fn  
some_fn()  
[–] Limitless_screaming@kbin.earth 2 points 2 months ago (1 children)

Yeah, that's the solution I asked about (last line of my question). I was just trying to make sure that this is ok and won't tangle up my code later on.

I'm not sure why you're using as to make the module name longer? Usually, if I use it at all, I use it make things shorter. Anyway, once you've imported dep2, you can call dep2.some_fn().

That was just for the example (clarifying order of import). The actual code has imports such as from src.formatter import Formatter as fmt; always making the name shorter.

Thanks for the suggestions

[–] tunetardis@piefed.ca 2 points 2 months ago

I was just trying to make sure that this is ok and won’t tangle up my code later on.

I guess the main issue there is Python doesn't like circular dependencies? Like if you try to import dep2 from dep1 and dep1 from dep2, you're going to have a problem. You'd essentially have to refactor your code to have a dep3 that both can import to use the common functionality I guess.