Equivalent to Perl's Data::Dumper

Skip Montanaro skip at pobox.com
Tue Aug 14 11:32:11 EDT 2001


    Heiko> I have looked through all of the Python documentation for now,
    Heiko> but I can't seen to find a module to do just this. What I'm
    Heiko> trying to do is inspect a variable at runtime. I know pickle can
    Heiko> do the job, but I can't/don't want to read the output it
    Heiko> produces. dir or inspect.getmembers won't do the job, they don't
    Heiko> run recursive (they just display the current members, nothing
    Heiko> below that). Isn't there some readymade module to recursively
    Heiko> look at a class or instance?

You might want to look at pprint module.  It's a pretty printer for
containers.  Don't know how well it will work with classes or instances, but
you can always feed it the class or instance dict.

Also, here are recursive (dirall) and non-recursive versions of dir I define
for interactive use:

    def dir(o=globals,showall=0):
        if not showall and hasattr(o, "__all__"):
            x = list(o.__all__)
            x.sort()
            return x
        from __builtin__ import dir
        return dir(o)

    def dirall(o, showall=0):
        attrs = dir(o, showall)
        if hasattr(o, "__bases__"):
            for b in o.__bases__:
                attrs.extend(dirall(b, showall))
        if hasattr(o, "__class__") and o != o.__class__:
            attrs.extend(dirall(o.__class__, showall))
        adict = {}
        for a in attrs:
            adict[a] = 1
        attrs = adict.keys()
        attrs.sort()
        return attrs

When set, the showall parameter will display all objects a module contains,
even if it defines a restrictive __all__ list.

The odd "o != o.__class__" in dirall catches some recursion in the data
structures involved in the latest ExtensionClass-based PyGtk wrappers for
Gtk+.  I don't know if that's a quirk of that implementation or is a general
property of ExtensionClass-based class hierarchies.  YMMV.

I believe the code above will work on 1.5.2 and newer versions of Python,
though I've only tested in on 1.6 and 2.x.

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list