Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows how to get the names and types of all the attributes of a Python module. This can be useful when exploring new modules (either built-in or third-party), because attributes are mostly a) data elements or b) functions or methods, and for either of those, you would like to know the type of the attribute, so that, if it is a data element, you can print it, and if it is a function or method, you can print its docstring to get brief help on its arguments, processsing and outputs or return values, as a way of learning how to use it.

The code for the recipe includes an example call to it, at the end of the code. Note that you first have to import the modules that you want to introspect in this way.

Python, 24 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from __future__ import print_function

# mod_attrs_and_types.py 
# Purpose: To show the attribute names and types 
# of a Python module, to help with learning about it.
# Author: Vasudev Ram
# Copyright 2016 Vasudev Ram
# Web site: https://vasudevram.github.io
# Blog: http://jugad2.blogspot.com
# Product store: https://gumroad.com/vasudevram

import sys

def attrs_and_types(mod_name):

    print('Attributes and their types for module {}:'.format(mod_name))
    print()
    for num, attr in enumerate(dir(eval(mod_name))):
        print("{idx}: {nam:30}  {typ}".format(
            idx=str(num + 1).rjust(4),
            nam=(mod_name + '.' + attr).ljust(30), 
            typ=type(eval(mod_name + '.' + attr))))

attrs_and_types(sys.__name__)

This recipe can be useful when exploring new modules (either built-in or third-party), because attributes are mostly a) data elements or b) functions or methods, and for either of those, you would like to know the type of the attribute, so that, if it is a data element, you can print it, and if it is a function or method, you can print its docstring to get brief info on its arguments, what processsing it does, and its outputs or return values, so you know how to use it.

This same task can also be achieved using some routines from the inspect module, but this is a simpler way of doing it, and does not require us to import the inspect module.

More info and sample output here:

http://jugad2.blogspot.in/2016/10/get-names-and-types-of-python-modules.html