0

I have two files, a.py and b.py. They are different branches of the same project (I checkout another branch in a separate directory with git). I have a third file c.py, that imports functions from both a.py and b.py to compare against each other.

My issue is a.py and b.py have nearly identical imports, but the content of what they're importing is often different because they are different branches. When I import the functions to be tested from each file (a.py and b.py) into c.py I need to add their paths to sys.path. When I do this b.py imports the same modules as a.py, rather than importing it's own or vice versa.

At the moment, I've just been adding an extra "directory" to the imports each time I make a new branch. So if I had import x, y, z originally in b.py (the non-master branch), I would add the path before the directory with those modules to sys.path and change the imports to branch_a.x as x, branch_a.y as y, branch_a.z as z... It doesn't take very long, but it would be nice to have an automated solution. Any ideas?

EDIT: Code for relative paths:

import sys
sys.path.append("./..")
tonyl7126
  • 1,548
  • 3
  • 14
  • 19

1 Answers1

1

You can set the PYTHONPATH environment variable to control which branch-root-dir to start looking for imported modules under.

Also recommended is to use relative-imports (see here) wherever they are appropriate. Done right, this would greatly reduce the dependency on environment/path settings. However, you'd still need to use env/path settings, because not all imports can/should become relative (e.g. to avoid too many up-level imports, and because imports in scripts cannot be relatvie).

Community
  • 1
  • 1
shx2
  • 61,779
  • 13
  • 130
  • 153
  • I've tried to use ../ (relative path of the imported modules), but run into an import error if I do so. For some reason, that isn't working. – tonyl7126 Oct 23 '13 at 19:14
  • You misunderstood the notion of relative imports. see http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports – shx2 Oct 23 '13 at 19:21