0

I have a directory structure like this:

PYTHONPATHDIR
 App1
 someModule.py
 utils.py 
 utils
 hasClassIWantToImport.py

And I want someModule to import something from utils.hasClassIWantToImport. When I call:

from utils.hasClassIWantToImport import ClassIWant

it cannot resolve "hasClassIWantToImport" because it thinks I'm talking about the utils.py in the current directory.

How do I get around this? I know I can rename one of the "utils" but would rather not...

asked Jul 6, 2012 at 18:22
1
  • 2
    It's not a good practice to give the same names to different modules/classes. Commented Jul 6, 2012 at 18:36

2 Answers 2

1

There isn't any way that you are going to be able to maintain access to both PYTHONPATHDIR/utils and PYTHONPATHDIR/App1/utils.py simultaneously without referring to one of them relative to something else.

If you modify your path so that PYTHONPATHDIR is at the head of the list, then you can import utils.hasClassIWantToImport but you will lose access to utils.py.

About the best you can do is make App1 a package by placing a __init__.py file into it and munge your path like @Gryphius suggested (i.e. put /path/to/utils at the head of sys.path). When you want access to utils.hasClassIWantToImport, you

from utils.hasClassIWantToImport import ClassIWant

To import files relative to utils.py, you will then

from App1.utils import ClassIWantFromApp1

However, this is a horrible hack just to avoid renaming utils.py. I recommend saving yourself the long-term headache of path manipulation and just rename that file.

answered Jul 6, 2012 at 20:30
Sign up to request clarification or add additional context in comments.

Comments

1

not sure if I have understood your directory setup correctly, but you could try:

import sys
sys.path.insert(0,'/path/to/utils')
from hasClassIwantToImport import ClassIWant
answered Jul 6, 2012 at 18:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.