Is there a python module that provides deeper analysis of a data structure than pprint?

Is there anything in python that lets me dump out a random object in such a way as to see its underlying data representation?

I am coming from Perl where Data::Dumper does a reasonable job of letting me see how a data structure is laid out. Is there anything that does the same thing in python?

Thanks!

-------------Problems Reply------------

Well Dumper in Perl gives you a representation of an object that can be eval'd by the interpreter to give you the original object. An object's repr in Python tries to do that, and sometimes it's possible. A dict's repr or a str's repr do this, and some classes like datetime and timedelta also do this. So repr is as much the equivalent of Dumper but it's not pretty and doesn't show you the internals of an object. For that you can use dir and roll your own printer.

Here's my shot at a printer that would not result in eval-able Python code and thus should be used to generate a string of the object instead:

def dump(obj):
out = {}

for attr in dir(obj):
out[attr] = getattr(obj, attr)

from pprint import pformat
return pformat(out)

class myclass(object):
foo = 'foo'

def __init__(self):
self.bar = 'bar'

def __str__(self):
return dump(self)

c = myclass()
print c

In the above example, I've overridden the object's default __str__ implementation. __str__ is what gets called when you try to represent the object as a string, or format it using a string formatting function.

BTW repr is what gets printed when you do print obj, it invokes the __repr__ method on that object. See the Python documentation of __repr__ for more information on how to control the formatting of objects.

# this would print the object's __repr__
print "%r" % c

# this would print the object's __str__
print "%s" % c


The output from the above code was

{'__class__': <class '__main__.myclass'>,
'__delattr__': <method-wrapper '__delattr__' of myclass object at 0xb76deb0c>,
'__dict__': {'bar': 'bar'},
'__doc__': None,
'__format__': <built-in method __format__ of myclass object at 0xb76deb0c>,
'__getattribute__': <method-wrapper '__getattribute__' of myclass object at 0xb76deb0c>,
'__hash__': <method-wrapper '__hash__' of myclass object at 0xb76deb0c>,
'__init__': <bound method myclass.__init__ of <__main__.myclass object at 0xb76deb0c>>,
'__module__': '__main__',
'__new__': <built-in method __new__ of type object at 0x82358a0>,
'__reduce__': <built-in method __reduce__ of myclass object at 0xb76deb0c>,
'__reduce_ex__': <built-in method __reduce_ex__ of myclass object at 0xb76deb0c>,
'__repr__': <method-wrapper '__repr__' of myclass object at 0xb76deb0c>,
'__setattr__': <method-wrapper '__setattr__' of myclass object at 0xb76deb0c>,
'__sizeof__': <built-in method __sizeof__ of myclass object at 0xb76deb0c>,
'__str__': <bound method myclass.__str__ of <__main__.myclass object at 0xb76deb0c>>,
'__subclasshook__': <built-in method __subclasshook__ of type object at 0x896ad34>,
'__weakref__': None,
'bar': 'bar',
'foo': 'foo'}

After much searching about for this exactly myself, I came across this Dumper equivalent which I typically import now. https://salmon-protocol.googlecode.com/svn-history/r24/trunk/salmon-playground/dumper.py

Category:python Views:0 Time:2010-07-11
Tags: python

Related post

  • Which Python modules provide good foundation classes for spatial data? 2011-01-01

    I am preparing to build an application in Python that works with a lot of spatial data. I am looking for a Python module that provides a nice set of spatially-enabled classes that I can inherit from. Two things I would like to have baked in are: Supp

  • What available Python modules are there to save-and-load data? 2012-01-17

    There are many scattered posts out on StackOverflow, regarding Python modules used to save and load data. I myself am familiar with json and pickle and I have heard of pytables too. There are probably more out there. Also, each module seems to fit a

  • What's the best way to make a deep copy of a data structure in Perl? 2008-12-23

    Given a data structure (e.g. a hash of hashes), what's the clean/recommended way to make a deep copy for immediate use? Assume reasonable cases, where the data's not particularly large, no complicated cycles exist, and readability/maintainability/etc

  • Python: How to estimate / calculate memory footprint of data structures? 2009-04-14

    What's a good way to estimate the memory footprint of an object? Conversely, what's a good way to measure the footprint? For example, say I have a dictionary whose values are lists of integer,float tuples: d['key'] = [ (1131, 3.11e18), (9813, 2.48e19

  • General Python modules 2012-05-02

    I see this question has been asked before, but I still trying to get my head around working with python modules. My app has a very basic structure: app/ __init__.py driver.py dbloader/ __init__.py loader.py both __init__.py files are empty. driver.py

  • Python data structure/object to model static multidimensional table 2009-11-23

    I'm just getting back into coding after a few year hiatus and I'm trying to model multi-tiered static forms in a way that lets me grab and perform operations on a specific form level or an entire sub-tree. Example Form hierarchy: MyForm Question 1 Pa

  • Data Structures in Python 2009-12-31

    All the books I've read on data structures so far seem to use C/C++, and make heavy use of the "manual" pointer control that they offer. Since Python hides that sort of memory management and garbage collection from the user is it even possible to imp

  • Best way to save complex Python data structures across program sessions (pickle, json, xml, database, other) 2010-01-05

    Looking for advice on the best technique for saving complex Python data structures across program sessions. Here's a list of techniques I've come up with so far: pickle/cpickle json jsonpickle xml database (like SQLite) Pickle is the easiest and fast

  • Stack data structure in python 2011-01-14

    I have 2 issues with the code below: push(o) throws an exception TypeError: can only assign an iterable. Should I throw an exception if pop() is invoked on an empty stack ? class Stack(object): def __init__(self): self.storage = [] def isEmpty(self):

  • Python Module Initialization Order? 2010-06-21

    I am a Python newbie coming from a C++ background. While I know it's not Pythonic to try to find a matching concept using my old C++ knowledge, I think this question is still a general question to ask: Under C++, there is a well known problem called

  • What's the difference between a Python module and a Python package? 2011-10-30

    What's the difference between a Python module and a Python package? See also: What's the difference between "package" and "module" (for other languages) --------------Solutions------------- A module is a single file (or files) that are imported under

  • Is there a python module for regex matching in zip files 2008-08-18

    I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files. Is there any python module which can do a

  • Python module for converting PDF to text 2008-08-25

    Is there any python module to convert PDF files into text? I tried one piece of code found in Activestate which uses pypdf but the text generated had no space between and was of no use. --------------Solutions------------- Try PDFMiner. It can extrac

  • listing all functions in a python module 2008-09-26

    I'm not a pythonista, so I'm not sure if this is really obvious or not. I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it so I can call the doc function on each one. In rub

  • Python module for wiki markup 2008-09-30

    Is there a Python module for converting wiki markup to other languages (e.g. HTML)? A similar question was asked here, What's the easiest way to convert wiki markup to html, but no Python modules are mentioned. Just curious. :) Cheers. --------------

  • Python module dependency 2008-10-01

    Ok I have two modules, each containing a class, the problem is their classes reference each other. Lets say for example I had a room module and a person module containing CRoom and CPerson. The CRoom class contains infomation about the room, and a CP

  • How do you organize Python modules? 2008-10-05

    When it comes to organizing python modules, my Mac OS X system is a mess. I've packages lying around everywhere on my hdd and no particular system to organize them. How do you keep everything manageable? --------------Solutions------------- My advice

  • How to avoid computation every time a python module is reloaded 2008-10-12

    I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I s

  • How do I find the location of Python module sources? 2008-11-06

    How do I learn where the source file for a given Python module is installed? Is the method different on Windows than Linux? --------------Solutions------------- For a pure python module you can find the source by looking at themodule.__file__. The da

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.086 (s). 11 q(s)