368

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?

littlejim84
  • 9,071
  • 15
  • 54
  • 77

28 Answers28

421

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.

Luke Singham
  • 1,536
  • 2
  • 20
  • 38
Brandon E Taylor
  • 24,881
  • 6
  • 47
  • 71
  • 34
    Didn't know the term was 'introspection'. That's a great help! Aswell as all the functons you've given me... Thank you! – littlejim84 Jun 17 '09 at 13:02
  • 3
    property, classmethod and staticmethod are not related to introspection. These methods all create special types of objects that can be used to define classes with special behavior, but are of no help at inspecting those classes or constructs. – SingleNegationElimination Jun 18 '09 at 00:21
  • The answer from @Brian below shows you how to also view the source code of various python objects from within python. That is what I was originally searching for and I'm sure I won't be alone. (It might be worth including a reference to his answer in this answer since it's the most accepted.) – michaelavila Feb 24 '12 at 19:24
  • It's like built-in **"IntelliSense"** for python. I love it. – Bruno Bieri Nov 10 '16 at 09:34
  • 10
    i think its a bad answer. instead of giving us a solution it just gives us everything related to that in the documentation – Ishan Srivastava Dec 29 '17 at 00:42
  • 1
    @IshanSrivastava was right. You're not supposed to provide links to answers, you're supposed to provide answers. – John Smith Jul 23 '21 at 08:36
225

object.__dict__

mtasic85
  • 3,905
  • 2
  • 19
  • 28
88

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.

Jason Baker
  • 192,085
  • 135
  • 376
  • 510
  • Then you use the other techniques mentioned here. But if the docstring is available, consider it canon. – Edward Falk Sep 30 '19 at 21:11
  • 1
    I'm not sure if python updated this function in the last few years, but "help(object_name)" provides a full overview in a highly structured format. It's a keeper. Thanks. – Brian Cugelman May 11 '20 at 05:25
68

First, read the source.

Second, use the dir() function.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
  • 5
    The source is more informative than dir() and a better habit to develop. – S.Lott Jun 17 '09 at 11:05
  • 16
    I beg to differ. dir() is just so much quicker and in 99% of the cases let's you find out what you need in combination with help(). – bayer Jun 17 '09 at 17:22
  • 7
    I agree with usuallyuseless. A lot of the time, a simple call to dir() will suffice, thus saving you the trouble of having to look through the source code. – Sasha Chedygov Jun 18 '09 at 00:13
  • 3
    Sometime inspecting objects at run time can be useful but reading sources not. E.g. httplib.py classes and their methods :). – Denis Barmenkov Jul 20 '12 at 16:07
31

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.

Brian
  • 116,865
  • 28
  • 107
  • 112
27

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

titusjan
  • 5,376
  • 2
  • 24
  • 43
13

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
)
Symon
  • 1,626
  • 1
  • 23
  • 31
12

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

bayer
  • 6,854
  • 24
  • 35
10

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.

wp78de
  • 18,207
  • 7
  • 43
  • 71
  • I try to learn structure of matches from opencv, but with no luck # python3 orb.py Traceback (most recent call last): File "orb.py", line 47, in pprint( matches[0]) TypeError: 'module' object is not callable print(matches[0]) # python3 orb.py Traceback (most recent call last): File "orb.py", line 48, in pprint( vars(matches[0])) TypeError: vars() argument must have __dict__ attribute – nerkn Aug 23 '20 at 12:22
9

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

0x90
  • 39,472
  • 36
  • 165
  • 245
8
"""Visit http://diveintopython.net/"""

__author__ = "Mark Pilgrim (mark@diveintopython.org)"


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__
njzk2
  • 38,969
  • 7
  • 69
  • 107
erenon
  • 18,838
  • 2
  • 61
  • 93
7

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.

Ryan Bright
  • 3,495
  • 21
  • 20
5

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

frmdstryr
  • 20,142
  • 3
  • 38
  • 32
4

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__

lprsd
  • 84,407
  • 47
  • 135
  • 168
3

pprint and dir together work great

sqram
  • 7,069
  • 8
  • 48
  • 66
3

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

Jonathan
  • 16,077
  • 12
  • 67
  • 106
3

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??

Sahar
  • 741
  • 1
  • 8
  • 14
3

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"}
oyinda david
  • 81
  • 1
  • 2
3

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
  >
>
minker
  • 510
  • 6
  • 3
2

vars(obj) returns the attributes of an object.

smonff
  • 3,399
  • 3
  • 36
  • 46
Omid Farvid
  • 785
  • 7
  • 13
2
import pprint

pprint.pprint(obj.__dict__)

or

pprint.pprint(vars(obj))
northtree
  • 8,569
  • 11
  • 61
  • 80
  • While this code may answer the question, providing additional context regarding **how** and/or **why** it solves the problem would improve the answer's long-term value. – Alexander Apr 05 '18 at 05:44
  • Is `pprint.pprint(vars(obj))` a wrapper for `print(str(obj.__dict__).replace(',',',\n'))`?(Legit question) Because I tried this answer expecting more information than what I was getting with `print(str(obj.__dict__).replace(',','\n'))` – dmb Jul 06 '21 at 07:01
  • @dmb Not just a wrapper. You can read source code. Here you are -> https://github.com/python/cpython/blob/main/Lib/pprint.py#L150 – northtree Jul 06 '21 at 10:46
2

Use the Rich Inspect:

my_list = ["foo", "bar"]
from rich import inspect
inspect(my_list, methods=True)
# use all=True for more information
# inspect(my_list, all=True) 

enter image description here

Lerner Zhang
  • 6,184
  • 2
  • 49
  • 66
1

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

>>> 
Mike McKerns
  • 33,715
  • 8
  • 119
  • 139
0

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

Mikhail Polykovskii
  • 2,333
  • 1
  • 16
  • 13
0

Are you looking for a way to read the whole content of the object?

After playing around Python a little bit, I feel like Python does not encourage us to read objects's content. Take JS for example: just a simple act of calling an object will list all the content of it, while in Python if an attribute is also an object, it doesn't write down that sub-object. I have to call that attribute explicitly for it to show up. If the attribute is an array of objects, it will only display the first attribute of each object in the array, not list them all.

Example:

vars(allnotes.notes[0])
{'path': WindowsPath('D:/Programming/test zone/example-vault/README.md'),
 'content': 'blabla',
 'metadata': <pyomd.metadata.NoteMetadata at 0x1b559874350>}

vars(allnotes.notes[0].metadata)
{'frontmatter': <class 'pyomd.metadata.Frontmatter'>:
 - dg_publish: True,
 'inline': <class 'pyomd.metadata.InlineMetadata'>:}

vars(allnotes.notes[0].metadata.inline)
{'metadata': {}}

I was told that objects in JS and objects in Python are conceptually different. A JS object is more like a Python dictionary. To the person I talked with, Python is well within what he'd call object oriented, Javascript is not at all.

I was advised to not use vars() or __dict__, just use the actual API of the classes. If an object isn't printing well without that introspection, then that's the devs fault for not writing proper string and print methods (usually via __repr__). Or in other words, Python defers the responsibility to display the objects to the dev, while JS takes that responsibility.

See more: When Should You Use .__repr__() vs .__str__() in Python?

Ooker
  • 1,969
  • 4
  • 28
  • 58
0

I just wanted to answer independently the following: You can use dir(). However, the specifics of using dir() may vary. This is what I personally do in order to introspect objects with dir() when I am programming a Python 2 or 3 script on a Windows 7 Intel processor desktop computer.

  1. I have a script that I want to debug or to learn about an object's functionality without referring to online directions.
  2. I modify the script so that it finishes running. The reason here is to enable the next step. Otherwise if the script runs a loop which doesn't end (like many programs i have using wxpython and pygame), I run [import pdb] and [pdb.set_trace()]
  3. I run the script from Geany by hitting the Execute button either in the toolbar or the menu or F5. With the build option Execute command set as ["C:\python36-32\python.exe" -i "%f"] without the square brackets. Located at Build -> Set Build Commands. You could do this with a .bat file or by changing your editor/IDE 's equivalent settings or with the shortcut properties or probably a bash script.
  4. After the .py script finishes executing, the -i flag that was shown above specifies that it go to the interpreter mode, where it shows >>>, and where you can enter normal python lines of code and hit enter to run them. And here you would be able to begin typing for example, [import os], then [dir(os)], at which point it would show you a list of things within "os", and then further [dir(os.abc)], [dir(os.abc.abstractproperty)], and [dir(os.abc.abstractpropperty.getter)] etcetera. To do this quicker you would usually use Up Arrow to recall the last command you entered (and hit return to run) into the interpreter. The difference when using pdb.set_trace() is that it looks different, you can type the command Continue to just go back to normal execution, and if you hit Ctrl+C to try to cancel what you're doing it will just end the program altogether as far as I know.
-2

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

object?
fmb
  • 889
  • 6
  • 6
-5

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__)

Ira Herman
  • 2,796
  • 1
  • 23
  • 22