Import aliases for moving a module?

Gabriel Genellina gagsl-py2 at
Sat Mar 28 07:17:31 CET 2009

En Thu, 26 Mar 2009 15:23:50 -0300, zopyxfilter at
<zopyxfilter at> escribió:

> For a while a maintained a Python package  'foo' with a number of
> modules (including a nested structure of module). Now the package
> moved into a namespace package
> ''. What is the way to approach making old code work with the
> new package in order
> that imports like
>  import
>  or
>  from import xxx
> remain working for existing code.

A quick and dirty solution is to have a foo package with an
that imports *every* single name in the old package, from the new one, and
puts it in sys.modules under the old name.

C:\temp>tree /f a

C:\temp>tree /f foo

C:\temp>type foo\
import warnings
warnings.warn("The 'foo' package is obsolete; use '' instead",
      DeprecationWarning, 2)

import sys
  from a.b import foo
  from import one, two
sys.modules[''] = one
sys.modules['foo.two'] = two

# very last line!
sys.modules['foo'] = foo
# now *this* module is gone

C:\temp>type a\b\foo\
print "This is", __file__, __name__

C:\temp>type a\b\foo\
print "This is", __file__, __name__

C:\temp>type a\b\foo\
print "This is", __file__, __name__

All other files are empty. Now, you can import foo and its
contents under the old and new names:

py> import foo
__main__:1: DeprecationWarning: The 'foo' package is obsolete; use
'' ins
This is a\b\foo\one.pyc
This is a\b\foo\two.pyc
py> import
py> import
<module '' from 'a\b\foo\one.pyc'>
<module '' from 'a\b\foo\one.pyc'>
py> is
py> import foo.two
py> import

Note that and are imported only once. *BUT* notice what
happens when you import, that was NOT included in foo\

py> import foo.three
This is a\b\foo\three.pyc foo.three
py> import
This is a\b\foo\three.pyc

That module was imported *twice*. So it's important to pre-import (inside
foo\ *every* name that was present in the old foo package. If
this is not feasible (there are many names, or loading all of them would
be too slow, or whatever) you may implement a "lazy" importer. See in the email package for an example.

Gabriel Genellina

More information about the Python-list mailing list