python 2.x and python 3 relative imports and

ptomulik at meil.pw.edu.pl ptomulik at meil.pw.edu.pl
Tue Nov 26 05:08:17 EST 2013


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 still have 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?



More information about the Python-list mailing list