'What is the Python equivalent of Ruby's "inspect"?

I just want to quickly see the properties and values of an object in Python, how do I do that in the terminal on a mac (very basic stuff, never used python)?

Specifically, I want to see what message.attachments are in this Google App Engine MailHandler example (images, videos, docs, etc.).



Solution 1:[1]

use the getmembers attribute of the inspect module

It will return a list of (key, value) tuples. It gets the value from obj.__dict__ if available and uses getattr if the the there is no corresponding entry in obj.__dict__. It can save you from writing a few lines of code for this purpose.

Solution 2:[2]

If you want to dump the entire object, you can use the pprint module to get a pretty-printed version of it.

from pprint import pprint

pprint(my_object)

# If there are many levels of recursion, and you don't want to see them all
# you can use the depth parameter to limit how many levels it goes down
pprint(my_object, depth=2)

Edit: I may have misread what you meant by 'object' - if you're wanting to look at class instances, as opposed to basic data structures like dicts, you may want to look at the inspect module instead.

Solution 3:[3]

Update

There are better ways to do this than dir. See other answers.

Original Answer

Use the built in function dir(fp) to see the attributes of fp.

Solution 4:[4]

I'm surprised no one else has mentioned Python's __str__ method, which provides a string representation of an object. Unfortunately, it doesn't seem to print automatically in pdb.

One can also use __repr__ for that, but __repr__ has other requirements: for one thing, you are (at least in theory) supposed to be able to eval() the output of __repr__, though that requirement seems to be enforced only rarely.

Solution 5:[5]

Try

repr(obj) # returns a printable representation of the given object

or

dir(obj) # the list of object methods

or

obj.__dict__ # object variables

Solution 6:[6]

Or unify Abrer and Mazur answers and get:

from pprint import pprint
pprint(my_object.__dict__ )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aaronasterling
Solution 2
Solution 3
Solution 4
Solution 5 Arkadiusz Mazur
Solution 6