2

I am using someone elses project to add some functionality to mine, and there is a python script I want to import. The problem comes with the import structure of their directories: I have placed their project directory in a subfolder under my main project (needs to stay there so I can keep their project out of my version control) it looks like this:

myproject/
  myscript.py
  theirproject/
    __init__.py
    baz.py
    secondlayer/
      __init__.py
      all.py
      foo.py
      bar.py

all.py is simply a list of import statements which import additional scripts from the secondlayer directory like this:

from secondlayer.foo import *
from secondlayer.bar import * #etc

I would like to import:

from theirproject.secondlayer.all import *

but that fails when python complains "no module named secondlayer.foo" I have also tried the following:

from theirproject.secondlayer import all

I can get it to work when I place my script in theirproject/ and import all without the "theirproject" prefix, but I really cant have it be like that. I can get further through the import process by importing foo, bar, etc individually like this:

from theirproject.secondlayer import foo
from theirproject.secondlayer import bar #etc

But then those scripts fail to import more stuff from still other scripts (like baz.py) at the same level as secondlayer, so im stuck.

Whats the right way to do this in python 2.7.6?

domoarigato
  • 2,802
  • 4
  • 24
  • 41

3 Answers3

1

If you change

from secondlayer.foo import *
from secondlayer.bar import *

to user relative imports like this

from .foo import *
from .bar import *

or like this

from foo import *
from bar import *

it works.

Plus you could do these imports in the __init__.py at secondlayer level so that the import from myscript.py becomes

from theirproject.secondlayer.all import *
junnytony
  • 3,455
  • 1
  • 22
  • 24
0

See if you have the necessary permissions to import the package from your directory and its corresponding sub directories.

For reference, you may like to see this and its corresponding linked questions :

Python Imports do not work

Community
  • 1
  • 1
Varun
  • 107
  • 3
  • 10
0

I ended up solving my problem by adding theirproject/ to my PYTHONPATH. I upvoted junnytony's answer - it helped point me in the right direction, so thanks!

domoarigato
  • 2,802
  • 4
  • 24
  • 41