0
src
 |
  -- Country
     |
      -- test_file.py -> test_file(function)
  -- State
     |
      -- test_file.py -> i want to run this file

I have to run the test_file in State which is the present working directory. I have to import the function test_file from test_file in country.

Using the path

import sys
sys.path.append('../Country')
from test_file import *

print test_file()

When i run the file. It says role_name function not found. It is not able to find the function. But if i change the name of the file in Country from test_file to some other name, Its working fine. I am thinking this problem has to do with some kind of ambiguousness.

I need to have the same name for both files. Is there another way out for this problem?

4
  • from ..Country.test_file import role_name…?! Commented Feb 28, 2017 at 13:45
  • Attempted relative import in non-package <-- gives this error. I dont have the luxury to run it in this format "python - m test_file.py" Commented Feb 28, 2017 at 13:50
  • The answers to this question might be helpfull: stackoverflow.com/questions/67631/… In the answers they show the use of importlib (python 3)/ imp (python 2). Commented Feb 28, 2017 at 13:50
  • print dir() and check the imported methods. Commented Feb 28, 2017 at 13:53

1 Answer 1

4

Replace sys.path.append('../Country') by sys.path.insert(0, '../Country')

Since you append your Country module at the end of the path, test_file.py in current working directory (State) will take precedence. Inserting at the beginning of the path should solve that. Also do not use import * but import role_path, this way the import directive will fail if the required object is not found, instead of silently continuing and letting errors trigger later.

But it would be a lot cleaner to just import your function this way, if Country is a proper module (with an __init__.py or not depending on the Python version):

from ..Country.test_file import role_path
Sign up to request clarification or add additional context in comments.

2 Comments

this makes sense. I've faced a similar problem before! and sys.path.insert() came to rescue!
sys.path.insert() worked like a charm. Thank you, Guillaume!

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.