Best way to print a module?

rantingrick rantingrick at gmail.com
Mon Sep 5 12:30:19 EDT 2011


On Sep 5, 10:06 am, Martin De Kauwe <mdeka... at gmail.com> wrote:
> 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

Martin, have you considered that your custom function is just re-
inventing the built-in dir() function? I would suggest using a list
comprehension against the dir() function with a predicate to remove
anything that startswith '_'. Here's some Ruby code to solve the
problem. I'll let you figure out the Python equivalent.

rb> ['_hello', '__goodbye__', 'whatsup'].select{|x| x[0].chr != '_'}
["whatsup"]




More information about the Python-list mailing list