1

I have a directory structure like this:

source\
  main\
    bar.py
    run.py
  A\
    foo.py

bar.py has functions which foo.py needs, so I use from bar import *, which works, as I've given foo.py the correct path to find bar.py. I verify this by running foo.py and calling any of the functions from bar.py without appending bar next to it. For example, if myFun is defined in bar.py, I can simply call myFun(...) in foo.py. This works all great so far.

run.py imports foo.py. However, when I try to run a function from foo.py which in turn uses a function imported from bar.py, Python claims myFun(...) does not exist. Note that myFun was originally defined in bar.py.

NameError: global name 'myFun' is not defined

The only way I managed to resolve this was to copy myFun into foo.py, but that is not really a solution.

user3898238
  • 957
  • 3
  • 11
  • 25
  • Not sure if it'd work, but you could try make a function in foo.py that executes myFun, and if not, why not just import bar.py into the run.py file? – Peter Nov 23 '14 at 01:49
  • Please provide code snippets. It'll be easier to understand exactly the semantics you are using when importing. – generalpiston Nov 23 '14 at 01:50
  • Do you have a different `bar.py` hanging around? In `foo.py`, add `import bar;print os.path.abspath(bar.__file__)`. Also, in foo.py, add `from bar import myFun` ... that should trigger the error earlier (and closer to the fault). – tdelaney Nov 23 '14 at 02:09
  • In `run.py`, are you doing `from foo import *`? Do you use the `__all__` variable in foo (that would mask the stuff you import)? – tdelaney Nov 23 '14 at 02:11

1 Answers1

1

You should avoid fiddling with the import paths as long as you have other options. In this case, create empty files main\__init__.py and A\__init__.py so Python recognizes these directories as packages, replace bar with main.bar in foo.py and run it from the top source directory.

Now, importing functions from foo.py to run.py should be as easy as:

from A.foo import fooFun1, fooFun2
user3426575
  • 1,723
  • 12
  • 18