Lorin Hochstein
Lorin Hochstein

Reputation: 59232

Check version of Python library that doesn't define __version__

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

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

Upvotes: 3

Views: 1065

Answers (4)

ltvolks
ltvolks

Reputation: 36

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

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

Upvotes: 2

Chris B.
Chris B.

Reputation: 90249

This being Python, the accepted way of doing this is generally to call something in the library that behaves differently depending on the version you have installed, something like:

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

A more elegant way might be to create wrapper functions.

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

Upvotes: 4

chmullig
chmullig

Reputation: 13416

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

Upvotes: 0

kindall
kindall

Reputation: 184280

If the library doesn't know its own version, then you are basically SOL. However, if one of the versions you want to support would raise an exception if the code went down the "wrong" path, you could use a try/except block.

Upvotes: 2

Related Questions