Renaming an import

dieter dieter at handshake.de
Fri Sep 6 01:13:55 EDT 2019


Rob Gaddi <rgaddi at highlandtechnology.invalid> writes:
> I'm trying to figure out how to rename an import globally for an
> entire package. Something like:
>
> pkg/__init__.py:
>     import graphing_module_b as graph
>
> pkg/foobar.py:
>     from .graph import plot, axis
>
> The point being that, if at some point I decide to change from
> graphing_module_b to graphing_module_a, that decision is made at a
> single central point in my package rather than scattered through 30
> different import statements in a dozen files.
>
> Any ideas?

You might have a look at `zope.deferredimport`.

Its primary task is to allow graceful handling of a change in package/module
structure: the Zope ecosystem consists of a huge number of independent
packages which should get time to adapt to such changes.
`zope.deferredimport` allows to define proxy modules as placeholders
for the original modules which relay imports to the new locations.
In addition, it generates warnings of the form "please import from ..."
to inform about the new structure.

That said: if you change the module structure, then I would recommend
that you change your own code accordingly and do not rely on
advanced features to keep the old names/locations: this makes understanding
of the code significantly more difficult.




More information about the Python-list mailing list