telliott99
telliott99

Reputation: 7907

Python project organization from sub-directories

I have a number of scripts with logical groups.

.
|_ database
|  |_ db.txt
|  |_ make_db.py
|
|_ accessory
|  |_ util.py
|
|_ explore_one_way
|  |_ script1.py
|
|_ explore_a_second_way
   |_ script2.py

How do I access, say, util.py from script1.py? Is there another way than adding to sys.path or is that the most pythonic?

Update: This is relatively painless. I added __init__.py to the accessory directory and can then do:

import sys
sys.path.insert(0, '..')
from proj import util

or

from proj.util import some_symbol

Thanks to all.

Upvotes: 0

Views: 147

Answers (3)

Subir Verma
Subir Verma

Reputation: 423

. |_ database | |_ db.txt | |_ make_db.py | |_ accessory | |_ util.py | |_ __init__.py | |_ explore_one_way | |_ script1.py | |_ explore_a_second_way |_ script2.py Make accessory a python package by adding init.py to it. Then do this

from accessory import util

Upvotes: 0

Frederik Bode
Frederik Bode

Reputation: 2744

You can:

  • add sys.path ((-) not very pythonic vs (+) easy)
  • use soft links ((-) sometimes gives issues with docker vs (+) you can link to directories). Soft links are a files that are like copies of other files, but not real copies (like a shallow copy). There's always only one copy of the file ever.
  • use hard links ((-) need to link every file, no directories vs (+) no docker issues). Hard links are actual copies that sync their clones if you change either one of them.

I recommend soft links if you don't like __init__.py and sys.path!

Upvotes: 1

MertG
MertG

Reputation: 763

Firstly, you should create empty __init__.py file each folder. Then add the top of your script1.py file as below.

import sys 
sys.path.insert(0, ".")

from accessory import util.py

Check out more

Upvotes: 2

Related Questions