DEAR PEOPLE FROM THE FUTURE: Here's what we've figured out so far...

Welcome! This is a Q&A website for computer programmers and users alike, focused on helping fellow programmers and users. Read more

What are you stuck on? Ask a question and hopefully somebody will be able to help you out!
+2 votes

Is there a way to know which version of a package is installed on the user's computer? I need to enable/disable functions based on that.


2 Answers

+2 votes

I wanted to know the answer to this also about a month ago. I had looked around. I thought poetry might be the best place to look. It seems like the version isn't a DRY value.

What this means is that while the packaging has a standard, the code does not. The __version__ seems like a good place by convention, but I don't see anything that enforces that.

I feel like this is something that is going to require an accepted PEP passing before we get anywhere on this.

I want to be proved wrong, though.

+1 vote

If you mean from the command line, either pip show <module> or pip freeze.

If you mean from code, I don't know if there is a standardized way to achieve this for all modules. Probably not, as @definitely_not_me has already explained well. Depending on where (and if) the version is specified, you can try one of these:

import <module>


from <module> import __version__
from <module> import version

if these don't work, you probably will need to investigate where the version is defined and try to read it.

It looks like there is a new module since Python 3.8, called importlib.metadata:

from importlib.metadata import version

For Python versions < 3.8 it looks like you can achieve something very similar to that by using pkg_resources (distributed with setuptools) but you have to use the package name, not the module name (for example "pyyaml" instead of "yaml"):

import pkg_resources

Ah, yeah thanks for reminding me about this one, I forgot about importlib.metadata.

It's probably the best there is right now, and it's also a good reason to upgrade to 3.8 and skip 3.7 if anyone is currently going through a 3.6 EOL code cleanup...

Contributions licensed under CC0