Relative imports in packages

Johannes Bauer dfnsonfsduifb at
Fri Nov 9 11:48:10 CET 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/ and contain their classes "Foo" and "Bar",
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


from pkg import Foo

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

However, when using a package this fails: Obviously, when I directly go
into the pkg/ subdirectory and try to execute, 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 contains a constant:

VERSION = "0.01"

>From my main program I can easily import that:

from pkg import VERSION

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

from . import VERSION

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

How do I do this right?

Thanks for your advice,
Best regards,

>> 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>

More information about the Python-list mailing list