How do I look inside a Python object?

PythonIntrospection

Python Problem Overview


I'm starting to code in various projects using Python (including Django web development and Panda3D game development).

To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties.

So say I have a Python object, what would I need to print out its contents? Is that even possible?

Python Solutions


Solution 1 - Python

Python has a strong set of introspection features.

Take a look at the following built-in functions:

type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively.

Solution 2 - Python

object.__dict__

Solution 3 - Python

I'm surprised no one's mentioned help yet!

In [1]: def foo():
   ...:     "foo!"
   ...:

In [2]: help(foo)
Help on function foo in module __main__:

foo()
    foo!

Help lets you read the docstring and get an idea of what attributes a class might have, which is pretty helpful.

Solution 4 - Python

First, read the source.

Second, use the dir() function.

Solution 5 - Python

If this is for exploration to see what's going on, I'd recommend looking at IPython. This adds various shortcuts to obtain an objects documentation, properties and even source code. For instance appending a "?" to a function will give the help for the object (effectively a shortcut for "help(obj)", wheras using two ?'s ("func??") will display the sourcecode if it is available.

There are also a lot of additional conveniences, like tab completion, pretty printing of results, result history etc. that make it very handy for this sort of exploratory programming.

For more programmatic use of introspection, the basic builtins like dir(), vars(), getattr etc will be useful, but it is well worth your time to check out the inspect module. To fetch the source of a function, use "inspect.getsource" eg, applying it to itself:

>>> print inspect.getsource(inspect.getsource)
def getsource(object):
    """Return the text of the source code for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a single string.  An
    IOError is raised if the source code cannot be retrieved."""
    lines, lnum = getsourcelines(object)
    return string.join(lines, '')

inspect.getargspec is also frequently useful if you're dealing with wrapping or manipulating functions, as it will give the names and default values of function parameters.

Solution 6 - Python

If you're interested in a GUI for this, take a look at objbrowser. It uses the inspect module from the Python standard library for the object introspection underneath.

objbrowserscreenshot

Solution 7 - Python

You can list the attributes of a object with dir() in the shell:

>>> dir(object())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Of course, there is also the inspect module: <http://docs.python.org/library/inspect.html#module-inspect>

Solution 8 - Python

Try ppretty

from ppretty import ppretty


class A(object):
    s = 5

    def __init__(self):
        self._p = 8

    @property
    def foo(self):
        return range(10)


print ppretty(A(), indent='    ', depth=2, width=30, seq_length=6,
              show_protected=True, show_private=False, show_static=True,
              show_properties=True, show_address=True)

Output:

__main__.A at 0x1debd68L (
    _p = 8, 
    foo = [0, 1, 2, ..., 7, 8, 9], 
    s = 5
)

Solution 9 - Python

While pprint has been mentioned already by others I'd like to add some context.

> The pprint module provides a capability to “pretty-print” arbitrary > Python data structures in a form which can be used as input to the > interpreter. If the formatted structures include objects which are not > fundamental Python types, the representation may not be loadable. This > may be the case if objects such as files, sockets, classes, or > instances are included, as well as many other built-in objects which > are not representable as Python constants.

pprint might be in high-demand by developers with a PHP background who are looking for an alternative to var_dump().

Objects with a dict attribute can be dumped nicely using pprint() mixed with vars(), which returns the __dict__ attribute for a module, class, instance, etc.:

from pprint import pprint
pprint(vars(your_object))

So, no need for a loop.

To dump all variables contained in the global or local scope simply use:

pprint(globals())
pprint(locals())

locals() shows variables defined in a function.
It's also useful to access functions with their corresponding name as a string key, among other usages:

locals()['foo']() # foo()
globals()['foo']() # foo()

Similarly, using dir() to see the contents of a module, or the attributes of an object.

And there is still more.

Solution 10 - Python

"""Visit http://diveintopython.net/"""

__author__ = "Mark Pilgrim ([email protected])"


def info(object, spacing=10, collapse=1):
	"""Print methods and doc strings.

	Takes module, class, list, dictionary, or string."""
	methodList = [e for e in dir(object) if callable(getattr(object, e))]
	processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
	print "\n".join(["%s %s" %
					 (method.ljust(spacing),
					  processFunc(str(getattr(object, method).__doc__)))
					 for method in methodList])

if __name__ == "__main__":
	print help.__doc__

Solution 11 - Python

Others have already mentioned the dir() built-in which sounds like what you're looking for, but here's another good tip. Many libraries -- including most of the standard library -- are distributed in source form. Meaning you can pretty easily read the source code directly. The trick is in finding it; for example:

>>> import string
>>> string.__file__
'/usr/lib/python2.5/string.pyc'

The *.pyc file is compiled, so remove the trailing 'c' and open up the uncompiled *.py file in your favorite editor or file viewer:

/usr/lib/python2.5/string.py

I've found this incredibly useful for discovering things like which exceptions are raised from a given API. This kind of detail is rarely well-documented in the Python world.

Solution 12 - Python

Two great tools for inspecting code are:

  1. IPython. A python terminal that allows you to inspect using tab completion.

  2. Eclipse with the PyDev plugin. It has an excellent debugger that allows you to break at a given spot and inspect objects by browsing all variables as a tree. You can even use the embedded terminal to try code at that spot or type the object and press '.' to have it give code hints for you.

enter image description here

Solution 13 - Python

If you want to look at parameters and methods, as others have pointed out you may well use pprint or dir()

If you want to see the actual value of the contents, you can do

object.__dict__

Solution 14 - Python

pprint and dir together work great

Solution 15 - Python

There is a python code library build just for this purpose: inspect Introduced in Python 2.7

Solution 16 - Python

If you are interested to see the source code of the function corresponding to the object myobj, you can type in iPython or Jupyter Notebook:

myobj??

Solution 17 - Python

In Python 3.8, you can print out the contents of an object by using the __dict__. For example,

class Person():
   pass

person = Person()

## set attributes
person.first = 'Oyinda'
person.last = 'David'

## to see the content of the object
print(person.__dict__)  

{"first": "Oyinda", "last": "David"}

Solution 18 - Python

There is a very cool tool called objexplore. Here is a simple example on how to use its explore function on a pandas DataFrame.

import pandas as pd
df=pd.read_csv('https://storage.googleapis.com/download.tensorflow.org/data/heart.csv')

from objexplore import explore
explore(df)

Will pop up the following in your shell: enter image description here

Solution 19 - Python

import pprint

pprint.pprint(obj.__dict__)

or

pprint.pprint(vars(obj))

Solution 20 - Python

If you are looking for a slightly more delicate solution, you could try objprint. A positive side of it is that it can handle nested objects. For example:

from objprint import objprint

class Position:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Player:
    def __init__(self):
        self.name = "Alice"
        self.age = 18
        self.items = ["axe", "armor"]
        self.coins = {"gold": 1, "silver": 33, "bronze": 57}
        self.position = Position(3, 5)

objprint(Player())

Will print out

<Player
  .name = 'Alice',
  .age = 18,
  .items = ['axe', 'armor'],
  .coins = {'gold': 1, 'silver': 33, 'bronze': 57},
  .position = <Position
    .x = 3,
    .y = 5
  >
>

Solution 21 - Python

If you want to look inside a live object, then python's inspect module is a good answer. In general, it works for getting the source code of functions that are defined in a source file somewhere on disk. If you want to get the source of live functions and lambdas that were defined in the interpreter, you can use dill.source.getsource from dill. It also can get the code for from bound or unbound class methods and functions defined in curries... however, you might not be able to compile that code without the enclosing object's code.

>>> from dill.source import getsource
>>> 
>>> def add(x,y):
...   return x+y
... 
>>> squared = lambda x:x**2
>>> 
>>> print getsource(add)
def add(x,y):
  return x+y

>>> print getsource(squared)
squared = lambda x:x**2

>>> 
>>> class Foo(object):
...   def bar(self, x):
...     return x*x+x
... 
>>> f = Foo()
>>> 
>>> print getsource(f.bar)
def bar(self, x):
    return x*x+x

>>> 

Solution 22 - Python

vars(obj) returns the attributes of an object.

Solution 23 - Python

In addition if you want to look inside list and dictionaries, you can use pprint()

Solution 24 - Python

Many good tipps already, but the shortest and easiest (not necessarily the best) has yet to be mentioned:

object?

Solution 25 - Python

Try using:

print(object.stringify())
  • where object is the variable name of the object you are trying to inspect.

This prints out a nicely formatted and tabbed output showing all the hierarchy of keys and values in the object.

NOTE: This works in python3. Not sure if it works in earlier versions

UPDATE: This doesn't work on all types of objects. If you encounter one of those types (like a Request object), use one of the following instead:

  • dir(object())

or

import pprint then: pprint.pprint(object.__dict__)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionlittlejim84View Question on Stackoverflow
Solution 1 - PythonBrandon E TaylorView Answer on Stackoverflow
Solution 2 - Pythonmtasic85View Answer on Stackoverflow
Solution 3 - PythonJason BakerView Answer on Stackoverflow
Solution 4 - PythonS.LottView Answer on Stackoverflow
Solution 5 - PythonBrianView Answer on Stackoverflow
Solution 6 - PythontitusjanView Answer on Stackoverflow
Solution 7 - PythonbayerView Answer on Stackoverflow
Solution 8 - PythonSymonView Answer on Stackoverflow
Solution 9 - Pythonwp78deView Answer on Stackoverflow
Solution 10 - PythonerenonView Answer on Stackoverflow
Solution 11 - PythonRyan BrightView Answer on Stackoverflow
Solution 12 - PythonfrmdstryrView Answer on Stackoverflow
Solution 13 - PythonlprsdView Answer on Stackoverflow
Solution 14 - PythonsqramView Answer on Stackoverflow
Solution 15 - PythonJonathanView Answer on Stackoverflow
Solution 16 - PythonSaharView Answer on Stackoverflow
Solution 17 - Pythonoyinda davidView Answer on Stackoverflow
Solution 18 - Python0x90View Answer on Stackoverflow
Solution 19 - PythonnorthtreeView Answer on Stackoverflow
Solution 20 - PythonminkerView Answer on Stackoverflow
Solution 21 - PythonMike McKernsView Answer on Stackoverflow
Solution 22 - PythonOmid FarvidView Answer on Stackoverflow
Solution 23 - PythonGladerView Answer on Stackoverflow
Solution 24 - PythonfmbView Answer on Stackoverflow
Solution 25 - PythonIra HermanView Answer on Stackoverflow