Reputation: 987
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.
Upvotes: 2
Views: 829
Reputation: 1773
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
Upvotes: 1