1

I have two python projects. The first one is a django project located at /path/to/project1/ and has below file structure:

project1/
 |- policy/
 |--- models.py

And I have another project, say project2. Within this project, I'd like to import the some definition from project1.policy.models. e.g.

 sys.path.append('/path/to/project1/')
 from policy.models import SomeModel

However, the issue is, in project2, there's also an directory named policy, which result in an ImportError. I cannot rename either directory name of policy. I do try absolute import, i.e. from __future__ import absolute_import but doesn't work.

BTW, my python version is 2.6.1

Gung Foo
  • 13,392
  • 5
  • 31
  • 39
Congbin Guo
  • 1,685
  • 2
  • 16
  • 16

2 Answers2

3

You can use the following to achieve your goal:

 project1/
     __init__.py
     policy/
         __init__.py
         models.py (contains SomeModels)

 project2/
     test_file.py
     policy/
         __init__.py

Above is your directory structure. Added is the _init_.py under project1/ so that you can import project1. Now in the test_file.py, you can do the following to achieve your goal:

sys.path.append('/path/to/project1/')
from project1.policy.models import SomeModel
ashokadhikari
  • 1,182
  • 3
  • 15
  • 29
0

Change your setup so you can do this:

sys.path.append('/path/to/')
from project1.policy.models import SomeModel
from project2.policy.models import SomeOtherModel

Just adding an empty __init__.py in /path/to/project1 and /path/to/project2 will do.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161