Library import succeeds with nose, fails elsewhere
rosuav at gmail.com
Sun Apr 26 00:46:16 CEST 2015
On Sun, Apr 26, 2015 at 3:48 AM, <richmolj at gmail.com> wrote:
> Apologies, I'm a rubyist and this is a beginner question but I'm not finding a great answer with lots of googling. I am writing a library, organized something like this:
> In the top of awesome.py:
> foo = 'bar'
> import helper
> In the top of helper.py:
> import awesome
> print awesome.foo
> IRL, I'm doing this for things like referring to the main logger from within the utility method.
I've lost track of the util directory here; you don't seem to be
mentioning it in your import anywhere. But I can recreate most of your
setup as a simple package:
$ grep -r $ .
./awesome/helper.py:from . import foo
./awesome/helper.py:print("My foo is %s" % foo)
./awesome/__init__.py:foo = 'bar'
./awesome/__init__.py:from . import helper
$ python2 foo.py
My foo is bar
$ python3 foo.py
My foo is bar
(I've tweaked your import and print syntax to make it Py3 compatible,
since it costs so little.)
The setup I'm using here is a straight-forward package. The first
thing imported will always be __init__.py, and modules within the
package (eg helper) can import from the package without problems,
because it'll always be loaded. It's still a circular dependency, but
it's a fairly clear and simple one.
Note that I'm being explicit about the intra-package imports here.
This is partly for Python 3 compatibility, but it's also for clarity;
"from . import foo" cannot accidentally import from a shadowing
module, but will only ever import a name from the package itself (it
might be another module, "foo.py", or it might be a name assigned
inside __init__.py, but it'll be from this package). When there's a
problem with imports somewhere, cutting down possible shadowing is a
great help with the debugging.
More information about the Python-list