How to check the versions of the modules installed in Python?

Asked

Viewed 5,334 times

2

I installed two modules in Python via anaconda (Conda install):

  • zipfile36;

  • Mysqldb.

Using the anaconda prompt I can get the version of both and all my other modules using the command:

conda list

But I would like to know, how directly in the code can I get the version of these modules? I have an application that I will need it.

  • 1

    Usually packages have in __init__.py a variable with the version. You can access the source code of each package and check which variable to evaluate.

2 answers

2


There is no 100% deterministic way for a module to inform its version. There are conventions and suggestions.

THE PEP 8 suggests here that a module variable called __version__ to store the version, however, this is only a suggestion - it is not required that modules have this variable.

Some modules follow this suggestion and make the version available in __version__, but others use alternative variables such as VERSION or VER or simply version. There are also modules that use a function get_version() capable of generating the number dynamically based on tags of the version control system used.

Luckily, both the MySQLdb as to the zipfile36 you want to use the method suggested by PEP 8. Then you can use:

import zipfile36
print(zipfile36.__version__)

import MySQLdb
print(MySQLdb.__version__)
  • Excellent, thank you very much! Luckily I will be able to use so rs

2

As a curiosity, I saw in this reply by Soen an alternative to the @nosklo response, where the module is used pkg_resources of setuptools.

import pkg_resources
pkg_resources.get_distribution("requests").version  # nome do pacote no PyPI
# '2.20.0'
  • great observation Fernando! I really tested here and also got the same result using ( version ) a good alternative also thank you!

  • It is worth remembering that the pkg_resources tries a variety of ways to search for the version of the module and if it can not find, is launched a ValueError. In the documentation I Linkei explains this.

  • I checked this, I did some tests and the error when not found is this: DistributionNotFound: The 'urllib' distribution was not found and is required by the application

  • But the module urllib is native, because you want to know the version of it? Just see the version of python then.

  • I didn’t want to, I just did a test to see how the error would come

  • It would have to be some lib installed by pip to test

  • I got it, there really wasn’t no attempt on that vlw!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.