![]() | Ned Batchelder : Blog | Code | Text | Site Python import helper » Home : Blog : June 2008 |
Python import helperWednesday 18 June 2008 Aptus has dependencies on three large packages, wxPython, Numpy, and PIL. The simple thing to do would be to import the modules and use the methods I need. But if the module is missing, an unhelpful ImportError message is all you get. And if the module is present, but isn't recent enough, then the method call may fail with a missing name. To solve these problems, I use this helper function instead: def importer(name): Then, instead of "import wx", I use: wx = importer("wx") and if anything goes wrong, the exception includes helpful details. This technique still suffers from the problem of detecting that the module is actually missing. Because of Python's impoverished exceptions, catching ImportError doesn't necessarily mean that the module was missing, although that's the most likely reason.
tagged:
python» 3 reactions | |
Comments
This seems somewhat crude. Isn't pkg_resources meant for exactly that purpose? It can even use a callback to install the missing package at the right version, IIUC.
As I was writing this up, I knew that eggs provided infrastructure that would do much of this. But I'm still not that fluent with eggs, it may well be a much better solution.
You could also have a look at PEP 302. Putting a marker at the end of sys.path and an importer that looks for this marker into sys.path_hooks you could get the above functionality with (probably) less code and you don't have to change your import statements.
Add a comment: