Getting a list of all modules

Skip Montanaro skip at pobox.com
Wed Jul 30 16:45:30 CEST 2014


On Wed, Jul 30, 2014 at 2:43 AM, Steven D'Aprano <steve at pearwood.info>
wrote:

> I'm looking for a programmatic way to get a list of all Python modules
> and packages. Not just those already imported, but all those which
> *could* be imported.
>

I wrote a modified dir(), which I inject into builtins in interactive
sessions. When getting a directory of an object, it attempts to identify
not-yet-imported modules it contains. Such modules are enclosed in square
brackets. Modules that smell like packages also get a trailing '/'. For
example:

% python
Python 2.7.5+ (2.7:2921f6c2009e, Apr 30 2014, 14:00:13)
[GCC 4.4.6 [TWW]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dateutil
>>> dir(dateutil)
['[easter]', '[parser]', '[relativedelta]', '[rrule]', '[tz]', '[tzwin]',
'[zoneinfo/]', '__author__', '__builtins__', '__doc__', '__file__',
'__license__', '__name__', '__package__', '__path__', '__version__']


It's not perfect, but works for my needs. Perhaps it will give you some
ideas.

Skip
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140730/038d5978/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: dir.py
Type: text/x-python
Size: 1875 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20140730/038d5978/attachment.py>


More information about the Python-list mailing list