4

Possible Duplicate:
Is there a function in Python to print all the current properties and values of an object?

In interactive python sessions I make a lot of use of the dir function, to get a sense of an object's structure. Unfortunately, dir only shows the names of attributes, not their values, so it is nowhere near as informative as it could be. Furthermore, dir's print out makes no attempt to format the output for ease of reading (IOW: dir don't do no stinkin' pretty-print).

Where can I find an "off-the-shelf" data-inspection utility that is more informative, and better formatted, dir?

For example, a more useful alternative to dir would print the values (suitably formatted, as needed) associated with each attribute, and would format this output for easy reading. For attributes whose values are callable, it would print their signatures and/or the first lines of their docstrings.

Thanks!

Community
  • 1
  • 1
kjo
  • 33,683
  • 52
  • 148
  • 265

3 Answers3

3

Try the inspect module, which can give you all sorts of things, including the original source code for a function, stack frames and more:

>>> class Foo:
...     def __init__(self, a, b, c):
...             self.a = a
...             self.b = b
...             self.c = c
...     def foobar(self):
...             return 100
... 
>>> f = Foo(50, 'abc', 2.5)
>>> import inspect
>>> inspect.getmembers(f)
[('__doc__', None), ('__init__', <bound method Foo.__init__ of <__main__.Foo instance at     0x7f0d76c440e0>>), ('__module__', '__main__'), ('a', 50), ('b', 'abc'), ('c', 2.5), ('foobar', <bound method Foo.foobar of <__main__.Foo instance at 0x7f0d76c440e0>>)]
>>> 
>>> def add5(x):
...     """adds 5 to arg"""
...     return 5 + x
... 
>>> inspect.getdoc(add5)
'adds 5 to arg'
>>> # What arguments does add5 take?
>>> inspect.getargspec(add5)
ArgSpec(args=['x'], varargs=None, keywords=None, defaults=None)
>>> # Format that nicely...
>>> inspect.formatargspec(inspect.getargspec(add5))
'((x,), None, None, None)'
>>> 
snim2
  • 4,004
  • 27
  • 44
1

If , by "object's structure" , you mean the instance attributes of the object, note that dir(something) calls something.__dir()__ if a user-defined method with name __dir__() exists, otherwise it inspects something.__dict__ and the type of something (I suppose it then calls the type's __dir__() or inspects the type's __dict__ )

Hence I believe that the instance attributes of an objects are given by its __dict__ attribute.

But some objects have no instance attributes, for example integers.

So, I think that if you test the existence of the __dict__ attribute of an object and, if it exists, obtaining its value will give you what you need to obtain : not only the names of the attributes but the objects so named.

Since you ask for formating of the output, I give this example with cPickle (a module is an object, as everything in Python)

import cPickle

for name,obj in  cPickle.__dict__.iteritems() :
    print '%-25s  -->  %r' % (name, obj)

result

load                       -->  <built-in function load>
PicklingError              -->  <class 'cPickle.PicklingError'>
__version__                -->  '1.71'
UnpickleableError          -->  <class 'cPickle.UnpickleableError'>
dump                       -->  <built-in function dump>
__builtins__               -->  <module '__builtin__' (built-in)>
Unpickler                  -->  <built-in function Unpickler>
compatible_formats         -->  ['1.0', '1.1', '1.2', '1.3', '2.0']
BadPickleGet               -->  <class 'cPickle.BadPickleGet'>
__package__                -->  None
dumps                      -->  <built-in function dumps>
UnpicklingError            -->  <class 'cPickle.UnpicklingError'>
PickleError                -->  <class 'cPickle.PickleError'>
HIGHEST_PROTOCOL           -->  2
__name__                   -->  'cPickle'
loads                      -->  <built-in function loads>
Pickler                    -->  <built-in function Pickler>
__doc__                    -->  'C implementation and optimization of the Python pickle module.'
format_version             -->  '2.0'

.

There's also the function help() that brings documentation you are searching for.

eyquem
  • 26,771
  • 7
  • 38
  • 46
  • 1
    `__dir__` is only available in Python 3. – Ethan Furman Jan 07 '12 at 04:27
  • 1
    @Ethan Furman I executed the code in my answer with Python 2.7, not in Python 3.x as it can be deduced from the way the printing instruction is written. ``__dict__`` exists at least from Python 1.5 (http://docs.python.org/release/1.5/lib/node270.html) – eyquem Jan 07 '12 at 14:42
  • 1
    @Ethan Furman I did a mistake, you don't speak of ``__dict__`` but ``__dir__``. You are right: there's a description in Python 3 and none in Python 2. But I think it's only an omission, concerning Python 2, because there's the same reference to a ``__dir__`` method in the description of ``dir``. Thanks to your comment, I realized that ``__dir__`` isn't a built-in method automatically created for some objects and not for others; it is a name reserved for the user's usage: if a user defines a user-defined method with this name, this method will automatically called by a call to ``dir()`` – eyquem Jan 07 '12 at 19:36
  • 1
    I said `__dir__`, not `__dict__`. However, it seems `__dir__` was added in 2.6, so thanks for the feedback. :) – Ethan Furman Jan 07 '12 at 19:48
0

Check out pprint

from pprint import pprint
pprint(object_you_want_to_see)
istruble
  • 13,363
  • 2
  • 47
  • 52
  • 1
    doesn't `inspect` or `dir` class attributes or object members, just runs the object's `.str()` or `.repr()` method and formats it. – hobs Mar 18 '12 at 04:41