Python Import Trickery
The use of 3rd party packages (i.e. through git submodules) you might run into an instance where a package requires a library that is not installed. If you use a 3rd party hosting solution and cannot modify your main installation there is an easy trick to aid in making these missing libraries importable.
Python’s sys.modules dictionary provides a simple mapping of modules to their namespaces. In my instance, I needed Python 2.5’s xml.etree.ElementTree to use tvdb_api. Since ElementTree is available as source for Python 2.4 I only needed to make it appear in that namespace. Here is the snippet of code which provides that functionality:
import types import ElementTree import xml sys.modules['xml'] = xml sys.modules['xml'].etree = types.ModuleType('xml.etree') sys.modules['xml.etree'] = sys.modules['xml'].etree sys.modules['xml.etree'].ElementTree = ElementTree sys.modules['xml.etree.ElementTree'] = sys.modules['xml.etree'].ElementTree
tvdb_api’s statementimport xml.etree.ElementTree now finds the proper library and executes without a hitch.
This is great! Thanks for this blog. I am a newbie at python and this will help a lot.
March 6th, 2010 at 7:30 pm