[Tutor] Finding the version # of a module, and py module problem

Philip Semanchuk philip at semanchuk.com
Thu Aug 5 21:47:48 EDT 2010


On Aug 5, 2010, at 8:55 PM, W. eWatson wrote:

> It's been awhile since I've used python, and I recall there is a way  
> to find the version number from the IDLE command line  prompt. dir,  
> help, __version.__?

Hi Wayne,
FYI it's got nothing to do with IDLE, it's just a question of whether  
or not the module in question exposes any kind of a version attribute.  
There's no standard, unfortunately. The most popular convention seems  
to be via an attribute called __version__, but I've also seen  
__VERSION__, VERSION, and version.

Here's some code that I wrote that you might find useful. It's from a  
setup.py and it checks a list of modules on which our project depends  
to see if (a) they're installed and (b) if the version installed is  
adequate. In the snippet below, dependencies is a list of custom  
classes that represent modules we need (e.g. numpy).


     # Try each module
     for dependency in dependencies:
         try:
             __import__(dependency.name)
         except ImportError:
             # Uh oh!
             dependency.installed = None
         else:
             # The module loaded OK. Get a handle to it and try to  
extract
             # version info.
             # Many Python modules follow the convention of providing  
their
             # version as a string in a __version__ attribute.
             module = sys.modules[dependency.name]

             # This is what I default to.
             dependency.installed = "[version unknown]"

             for attribute_name in ("__version__", "__VERSION__",  
"VERSION",
                                    "version"):
                 if hasattr(module, attribute_name):
                     dependency.installed = getattr(module,  
attribute_name)
                     break

Hope this helps a little,
Philip




More information about the Python-list mailing list