0

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.

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I think you want ".."
1

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!

1 Comment

I was afraid of that.
0

. |_ 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

2 Comments

This raises ImportError.
Not sure if you are maintaining the same directory structure. But try from .accessory import util

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.