Site icon This and That

Get Package version inside Python

A backwards-compatible mechanism to get version of installed package


try:
    from importlib.metadata import version as package_version, PackageNotFoundError
except:
    import pkg_resources

def get_package_version(name):
    version = 'None'
    use_fallback = False
    try:
            temp = package_version
    except NameError: 
            use_fallback = True

    if use_fallback:
            try:
                    version = pkg_resources.get_distribution(name).version
            except pkg_resources.DistributionNotFound:
                    version = 'None'
    else:
            try:
                    version = package_version(name)
            except PackageNotFoundError:
                    version = 'None'

    return version

print(get_package_version("psutil"))
Exit mobile version