Relative imports in packages

Johannes Bauer dfnsonfsduifb at gmx.de
Fri Nov 9 05:48:10 EST 2012


Hi list,

I've these two minor problems which bothered me for quite some time,
maybe you can help me. I'm using Python 3.2.

For some project I have a component in its own package. Let's say the
structure looks like this:

pkg/__init__.py
pkg/Foo.py
pkg/Bar.py

Foo.py and Bar.py contain their classes "Foo" and "Bar", __init__.py
looks like this:

from .Foo import Foo
from .Bar import Bar

This allows me to "naturally" access classes, i.e. from my main program:

import pkg
pkg.Foo("initme")

or

from pkg import Foo
Foo("initme")

So far, so good. Now let's say Bar uses Foo, i.e. in Bar's header is
something like:

from .Foo import Foo

If this all weren't a package the declaration would just read "from Foo
import Foo" and I could easily append a small unit-test to Bar:

if __name__ == "__main__":
	# test
	pass

However, when using a package this fails: Obviously, when I directly go
into the pkg/ subdirectory and try to execute Bar.py, the import of Foo
fails and it doesn't work. Is there a nice solution to this or am I
doing it all wrong?

Then another minor question: Let's say my __init__.py contains a constant:

VERSION = "0.01"

>From my main program I can easily import that:

from pkg import VERSION
print(VERSION)

However, from Foo.py, I cannot seem to get the syntax right:

from . import VERSION

  File "Foo.py", line 10, in <module>
    from . import VERSION
ImportError: cannot import name VERSION

How do I do this right?

Thanks for your advice,
Best regards,
Johannes

-- 
>> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
 - Karl Kaos über Rüdiger Thomas in dsa <hidbv3$om2$1 at speranza.aioe.org>



More information about the Python-list mailing list