3

Suppose I have the following (project1 is on python path):

/project1/utils/utils.py def cool_function(): print "cool" /project1/backup/utils.py from utils.utils import cool_function 

This throws "ImportError: No module named utils".

I assume this is because it is searching for utils.cool_function in backup.utils. Is there a rather than renaming the utils package? I think my naming convention makes sense, and is natural, so I'm reluctant to changing it. If that however is preferred and standard practice, I will rename it!

Thanks!

EDIT: I am using Python 2.7

3 Answers 3

2

You may use relative imports:

from ..utils.utils import cool_function 
Sign up to request clarification or add additional context in comments.

2 Comments

This doesnt work! Not sure why, I did try it myself before posting to SO.
I tried with Python27 and get "ValueError: Attempted relative import beyond toplevel package"
1

If project1 is a package (parent dir is on sys.path and has an __init__.py), you can do from project1.utils.utils import cool_function. See also PEP328, which is new in python 2.5. If you're using 2.5 or later, from ..utils.utils import cool_function may also work.

4 Comments

I also think this is a good way to do it. Use project1 to differentiate between; project1.utils.utils and project1.backup.utils. If project1 is in sys.path as you say this will also help if you will want to run the project from some other folder like: python folder1/folder2/project1/run.py
Actually, /project1/ is on the path, so I can refer to backup or utils directly when importing. Should put them in a wrapper package?
In many cases it's a judgement call, but as a general rule I'd say yes - if you ever need to integrate this project with others, it'd be problem if they also have 'utils' or 'backup' top-level packages. That generally doesn't happen - but it's for this reason.
I'm inclined to agree. I've moved everything into a super package and I already feel better about it. Everything is imported using the root package name (e.g. project1.utils.utils) as suggested, and it all works now. Thanks everyone.
0

Works fine with me.

With the following project structure:

project/ |-- run.py `-- utils | |-- __init__.py | |-- utils.py |-- backup |-- __init__.py |-- utils.py 

Where you call python3 run.py from the project directory.

Edit: Sorry I just saw that this does not apply to python-2.x.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.