Handle ImportError in Python
Python throws an ImportError if a module cannot be found.
Usually, there are two reasons for that.
Either the module is not installed or it’s location not in sys.path
.
Installing the module is hopefully trivial.
Putting it’s location to the path is either done by the environment variable PYTHONPATH
or programmatically:
Sometimes, you’re not sure about the environment the script will run but you need to a very specific module available. While you know how to make the module available, you somehow need to pass this information to the end user. It could be a little check in your code:
Obviously, you should rather provide documentation on how to setup the environment to run your code or even better provide provisioning scripts. However, when talking about small helper scripts that get passed around in the company, this is actually a nice thing to do. The original developer won’t get bothered, the end users is happy about the intelligent script and no additional documentation is needed.
I say “helper script” and I mean it: No production code, no customer facing code, not even scripts for other departments should have such a workaround. But it’s perfect for that handy little script that gets some internal stuff.