0

First off all: Sorry - I know that there already exist several questions which concern issues with the python import mechanism. However after hours of searching through SO I still couldn't find a sufficent answer for me.

Problem

I've got two independent Python projects hosted on my GitLab Server. Let's call them foo and foo-Tester. As the name implies, foo-Tester is a automatic Tester for the foo-Project.

foo has the following structure:

-foo
  - __init__.py
  - fooClass.py
  -bar
     - __init__.py
     - barClass.py
  -foobar
     - __init__.py
     - foobarClass.py
   etc.

The classes import each other via relativ imports.

For sake of this example the foo-Tester Project just contains:

- foo-Tester
   - __init__.py
   - tester.py

While the tester.py just contains:

from foo.fooClass import fooClass
myfoo = fooClass()

Both Projects reside next to each other on the file-system:

- some-folder
   - foo
   - foo-Tester

So my question is: What is the best approach/best-practice to import the fooClass from foo into tester.py from the foo-Tester-Project?

What I've tried

Using setup.py

Some Answers (e.g. this suggest using setup.py. As far as I understand this approach, one would need to install the foo-Project each time it is changed - am I correct? This wouldn't be a good solution for us as the Project is under heavy development with many changes a day.

Appending to system-path

This answer suggest adding the foo project path to the system path. And running the script with the -m Flag

Two concerns about this approach:

  • it seems a bit hacky to modify the systempaths
  • it seems like this doesn't work with the relative imports from the foo project as it always throws an relative imports not allowed-Error.

I am using Python 3.6. So what would be the best approach for the described problem?

Thank you in advance!

GuyWithCookies
  • 630
  • 2
  • 8
  • 21
  • I'm not sure why you need to do anything. Since both folders contain `__init__.py` files, they are packages; so `from foo.fooClass import fooClass` should work fine. Note, to import anything from foo-Tester you should change its name to a valid Python identifier, eg `foo_tester`. – Daniel Roseman Jun 14 '18 at 14:21

1 Answers1

0

From the thread out here: Importing modules from parent folder , this is the way how you can import modules from parent (or any other) folder.

import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir) 

import mymodule
user5214530
  • 467
  • 5
  • 11
  • Thanks for the suggestion. However this seems to me like a hacky workaround as well. Isn't there a more simple/ straight forward approach to this general problem? – GuyWithCookies Jun 15 '18 at 06:00