While debugging, deployment or during your DevSecOps strategy you want to print, write to a log, or whatever, your package version.

I have been dealing with this stuff for long, and I’m typically using the next approach using pkg_resources:

The package is expected to be installed using a setup.py containing name value as mysamplepackage in this example.

Remember to import pkg_resources in order to use this function.

import pkg_resources

You can also use, for modern Python versions, distribution functions from importlib_metadata package

 from importlib_metadata import distribution

It works in a similar way so the code would be

What’s your way? More on https://twitter.com/jdelafuente