Check version of Python library that does not detect __version__

I am dealing with a Python library that does not define the __version__ ( sqlalchemy-migrate ) variable , and I want to have different behavior in my code based on which version of the library I installed.

Is there a way to check at runtime which version of the library is installed (except, say, checking the output pip freeze)?

+3
source share
4 answers

pkg_resources may help, but you will need to use the package name:

>>> import pkg_resources
>>> env = pkg_resources.Environment()
>>> env['sqlalchemy-migrate'][0].version
'0.6.2.dev'
+2
source

This is Python, the accepted way to do this, as a rule, calls something in the library, which behaves differently depending on the version you installed, for example:

import somelibrary
try:
    somelibrary.this_only_exists_in_11()
    SOME_LIBRARY_VERSION = 1.1
except AttributeError:
    SOME_LIBRARY_VERSION = 1.0

-.

def call_11_feature():
    try:
        somelibrary.this_only_exists_in_11()
    except AttributeError:
        somelibrary.some_convoluted_methods()
        somelibrary.which_mimic()
        somelibrary.the_11_feature()
+3

If the library does not know its own version, then you are basically SOL. However, if one of the versions you want to support will throw an exception, if the code changes in the "wrong" way, you can use the try/ block except.

+2
source

Sometimes you can evaluate the library path and it will be somewhere there ... /usr/lib/python2.6/site-packages/XlsXcessive-0.1.6-py2.6.egg

0
source

Source: https://habr.com/ru/post/1792077/


All Articles