391

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?

30 Answers 30

448

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Didn't know the term was 'introspection'. That's a great help! Aswell as all the functons you've given me... Thank you!
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.
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.)
i think its a bad answer. instead of giving us a solution it just gives us everything related to that in the documentation
@IshanSrivastava was right. You're not supposed to provide links to answers, you're supposed to provide answers.
|
240

object.__dict__

5 Comments

vars(object) is made for that.
Actually from pprint import pprint; pprint(vars(object)) gave me a really nice view on the contents of my object. Thanks @liberforce
the best way to see object and its contents in a string
This is a great way to see objects which implement any representation methods, or objects like googleapiclient.errors.HttpError which when you print them they print insufficient information for sure, thanks @mtasic85
succinct star response
94

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.

2 Comments

Then you use the other techniques mentioned here. But if the docstring is available, consider it canon.
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.
67

First, read the source.

Second, use the dir() function.

6 Comments

The source is more informative than dir() and a better habit to develop.
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().
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.
Sometime inspecting objects at run time can be useful but reading sources not. E.g. httplib.py classes and their methods :).
Caveat: python source code is some of the worst Ive seen in 25 years of web development. "Reading the source" is helpful when it is built with intentional practices and principles and designed with professionalism. Thats rarely the case with a python package.
|
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.

Comments

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

Comments

15

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 ) 

Comments

13

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.

1 Comment

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 <module> pprint( matches[0]) TypeError: 'module' object is not callable print(matches[0]) <DMatch 0x7f7e8b5270> # python3 orb.py Traceback (most recent call last): File "orb.py", line 48, in <module> pprint( vars(matches[0])) TypeError: vars() argument must have dict attribute
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

Comments

11

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

1 Comment

Really cool useful thing! Is there a way to interact with it in Jupyter notebook?
9
"""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__ 

1 Comment

This works fine in python 3 if you just add parens around the prints.
9

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

Comments

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.

Comments

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

Comments

5

vars(obj) returns the attributes of an object.

2 Comments

Of a dictionary*
super simple & no need for external library +1
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__

Comments

4

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"} 

Comments

3

pprint and dir together work great

Comments

3

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

Comments

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

Comments

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

Comments

2
import pprint pprint.pprint(obj.__dict__) 

or

pprint.pprint(vars(obj)) 

3 Comments

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.
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 Not just a wrapper. You can read source code. Here you are -> github.com/python/cpython/blob/main/Lib/pprint.py#L150
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 >>> 

Comments

1

squiz can do that.

It will print out the members and nested members of your object (or class):

squiz_example.png

Comments

0

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

Comments

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?

Comments

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.

Comments

0

There is a builtin help system in Python. It is accessible through the builtin function help(). It is basically a man page for your object.

For example, if I declare a class Foo such as :

class Foo: """A simple example class""" bar = 123412 def foobar(self): return 'Hello world' 

The help function would give the following output (using a pager so it doesn't override your terminal and you can quit it with q).

Help on class Foo in module builtins: class Foo(object) | A simple example class | | Methods defined here: | | foobar(self) from Foo | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | bar = 41324 

This help page is for your class and not for its instances. For example, if you created the object foo and set its variable baz:

>>> foo = Foo() >>> foo.baz = 12042 

The help(foo) command (note the lowercase for foo) would yield the same help page as before.

To print the definitions from the instantiated object, you can resort to the vars() builtin with would print the following to stdout:

>>> vars(foo) {'baz': 12042} 

Comments

-2

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

object? 

1 Comment

It works, but if the object is a big list, you're gonna have a bad time
-4

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

1 Comment

Doesn't work on a 'Request' object "'Request' object has no attribute 'stringify'"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.