Best way to print a module?

Martin De Kauwe mdekauwe at gmail.com
Mon Sep 5 17:06:10 CEST 2011


Hi,

If I wanted to print an entire module, skipping the attributes
starting with "__" is there an *optimal* way? Currently I am doing
something like this. Note I am just using sys here to make the point

import sys

data = []
for attr in sys.__dict__.keys():
    if not attr.startswith('__') and not attr.endswith('__'):
        attr_val = getattr(sys, attr)
        data.append((attr, attr_val))
data.sort()
for i in data:
    print "%s = %s" % (i[0], i[1])

Clearly this would be quicker if I didn't store it and sort the
output, i.e.

for attr in sys.__dict__.keys():
    if not attr.startswith('__') and not attr.endswith('__'):
        attr_val = getattr(sys, attr)
        print "%s = %s" % (attr, attr_val)

Anyway if there is a better way it would be useful to hear it...

Many thanks,

Martin



More information about the Python-list mailing list