| I l@ve RuBoard |
|
14.2 The pyclbr ModuleThe pyclbr module, shown in Example 14-1, contains a basic Python class parser. In 1.5.2, the module exports a single function, readmodule, which parses a given module, and returns a list of all classes defined at the module's top level. Example 14-1. Using the pyclbr Module
File: pyclbr-example-1.py
import pyclbr
mod = pyclbr.readmodule("cgi")
for k, v in mod.items():
print k, v
MiniFieldStorage <pyclbr.Class instance at 7873b0>
InterpFormContentDict <pyclbr.Class instance at 79bd00>
FieldStorage <pyclbr.Class instance at 790e20>
SvFormContentDict <pyclbr.Class instance at 79b5e0>
StringIO <pyclbr.Class instance at 77dd90>
FormContent <pyclbr.Class instance at 79bd60>
FormContentDict <pyclbr.Class instance at 79a9c0>
In 2.0 and later, there's also an alternative interface, readmodule_ex, which returns global functions as well. This is shown in Example 14-2. Example 14-2. Using the pyclbr Module to Read Classes and Functions
File: pyclbr-example-3.py
import pyclbr
# 2.0 and later
mod = pyclbr.readmodule_ex("cgi")
for k, v in mod.items():
print k, v
MiniFieldStorage <pyclbr.Class instance at 00905D2C>
parse_header <pyclbr.Function instance at 00905BD4>
test <pyclbr.Function instance at 00906FBC>
print_environ_usage <pyclbr.Function instance at 00907C94>
parse_multipart <pyclbr.Function instance at 00905294>
FormContentDict <pyclbr.Class instance at 008D3494>
initlog <pyclbr.Function instance at 00904AAC>
parse <pyclbr.Function instance at 00904EFC>
StringIO <pyclbr.Class instance at 00903EAC>
SvFormContentDict <pyclbr.Class instance at 00906824>
...
To get more information about each class, use the various attributes in the Class instances, as Example 14-3 shows. Example 14-3. Using the pyclbr Module
File: pyclbr-example-2.py
import pyclbr
import string
mod = pyclbr.readmodule("cgi")
def dump(c):
# print class header
s = "class " + c.name
if c.super:
s = s + "(" + string.join(map(lambda v: v.name, c.super), ", ") + ")"
print s + ":"
# print method names, sorted by line number
methods = c.methods.items()
methods.sort(lambda a, b: cmp(a[1], b[1]))
for method, lineno in methods:
print " def " + method
print
for k, v in mod.items():
dump(v)
class MiniFieldStorage:
def _ _init_ _
def _ _repr_ _
class InterpFormContentDict(SvFormContentDict):
def _ _getitem_ _
def values
def items
...
|
| I l@ve RuBoard |
|