python 2.x and python 3 relative imports and

P

ptomulik

Hi,

let say I have a legacy code with the following structure:

pkg1/__init__.py
pkg1/pkg2/__init__.py
pkg1/pkg2/bar.py
pkg1/pkg2/pkg3/__init__.py
pkg1/pkg2/pkg3/foo.py


In pkg1/pkg2/bar.py I have:

# pkg1/pkg2/bar.py
import pkg3.foo
class Bar(pkg3.foo): pass

in pkg1/pkg2/pkg3/foo.py:

# pkg1/pkg2/pkg3/foo.py
class Foo: pass

Now I want to adapt bar.py such that it works in Python 3, but without modifying the definition of Bar class (I wan't restrict modification to import directives). My first thought was that I to just modify the import directive, such that the 'pkg3.foo' would be still available in bar.py. Unfortunately I can't find any way to do it. Obviously, this relative import is not going to work:

from . import pkg3.foo

because it's a syntax error (pkg3.foo is not an identifier). This is accepted by python:

from .pkg3 import foo

but it binds 'foo' instead of 'pkg3' to the local (bar) module, and I stillhave no access to 'pkg3.foo'.

The only way I found do have 'pkg3.foo' in 'bar' is this two-line trick:

from . import pkg3
from .pkg3 import foo

or

from . import pkg3
import pkg1.pk2.pk3.foo

but this clutters local (bar) namespace with symbols 'foo' (first case) or 'pkg1' (second approach).

Do you know any other way for relative imports to achieve exactly same effect as with old import semantics?
 

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

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top