Relative imports in packages


Johannes Bauer

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,

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 <[email protected]>


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question