DEV Community

spO0q
spO0q

Posted on

Python: prevent import errors

I've already asserted in this series that you should catch errors in your Python scripts.

Not only that it improves user experience, but it may save you some precious time if you provide support.

What are imports?

Imports can simply consist of calling a third-party package in your script to speed up development or avoid reinventing the wheel.

It's usually done this way in Python:

import my_awesome_package
Enter fullscreen mode Exit fullscreen mode

But you can also alias it:

import my_awesome_package as another_name
Enter fullscreen mode Exit fullscreen mode

When you start sharing your code, you need to tell people how to install all dependencies to prevent bad import errors.

Indeed, if "my_awesome_package" is a third-party package that is not pre-installed with Python, users will get a fatal error.

Fortunately, Python has its own package manager Pip that comes with Python, so Python devs usually put a file called requirements.txt at the root of their projects to indicate third-party modules to install.

Then, users only have to use the following command:

pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

Devs are lazy, so are users

We all know that we must read the Fabulous documentation (RTFM), but, in practice, it's often skipped.

Whether it's good or bad (mostly bad) is not our problem here. People just do that.

However, you can add some extra check:

import sys

try:
    import my_awesome_package
except ModuleNotFoundError:
    print("Please run 'pip install -r requirements.txt' to use this script.")
    sys.exit(1)
Enter fullscreen mode Exit fullscreen mode

While it's not an official recommendation from the documentation, I like to include such checking.

Wrap up

Catching import errors can be beneficial even if it adds a few lines in your script.

Top comments (0)