I was trying to edit setup.py, so it could have a requirement like “either Foo or Bar”, but it doesn’t seem to be possible. So I wrote the following code to help.

import pkg_resources

try:
    pkg = pkg_resources.get_distribution('package_name')
    if pkg.has_version():
        print(pkg.version)
except pkg_resources.DistributionNotFound:
    print('not installed')

This is not really doing the || part. If first package is installed, then it will be used to form the install_requires, or use second package to form, but this not really I want to show in this blog post.

If no exception raises, it means that package is installed. You can be safely presumed you could perform import, however, it doesn’t mean the package or module can be imported successfully.

Checking a Python package might be useful as doing like the code above. Of course, you could try to import but that would be terrible if that package or module is really a big one, you should never let setup.py to perform importing just to check if dependency requirement is met. Speaking of that, I might need to fix some of my setup.py.

Besides, with this way, you can get the version string more reliable, module.__VERSION__ may not be coded in every package or module.