rds
rds

Reputation: 26994

How to get module information without loading it?

I know the imp module can be used in Python 3 to load modules and packages.

However, I'd like to get some information about a module (like __version__) before I actually loads it.

How can I get this information? I haven't found any useful method in imp.

Right now, I cannot see better than parsing myself the file found by imp.find_module.

Upvotes: 2

Views: 770

Answers (2)

Lennart Regebro
Lennart Regebro

Reputation: 172309

This depends on what the module is, and if it's installed or not, etc. You want __version__ for example, but there is nothing that is guaranteed to exist in a module. The standard attributes you have on a module, like __cached__, __doc__, __file__, __name__, __package__ are all created when you import it.

If the module is not yet installed, ie it's a downloaded tgz or something, it will probably have a setup.py file, and then you can get a lot of information from that distribution if you extract it with distutils. I do this in pyroma, for example.

If it is installed it may have an EGG-INFO directory. In there you find a bunch of files, with a lot of information. Most of it is in the PKG-INFO file. For this to happen, each of your modules must use Distribute (or Setuptools).

If it has no EGG-INFO/PKG-INFO file then you will have to parse it. For __version__ you can probably just do a regexp match. That will not be very generic, but then again, whatever information you look for will not be generic, and will most likely not exist unless you know exactly what module you are looking at.

For other things you might need a parser. ast is probably the best option there, although the parser in lib2to3 has it's good sides as well.

Upvotes: 1

Cat Plus Plus
Cat Plus Plus

Reputation: 129894

You can't. __version__ is just name for an object the module creates while being executed. It doesn't exist until you execute the file that's responsible for defining the module. Parsing is one option, but it'll work only if the code defining __version__ is trivial, e.g.

__version__ = 'some literal'

If it involves something more, then you have to execute the code at least partially.

Upvotes: 4

Related Questions