Reputation: 9301
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?
Upvotes: 388
Views: 521881
Reputation: 180
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}
Upvotes: 0
Reputation: 8999
squiz can do that.
It will print out the members and nested members of your object (or class):
Upvotes: 1
Reputation: 39
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.
Upvotes: 0
Reputation: 3086
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?
Upvotes: 0
Reputation: 7150
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)
Upvotes: 8
Reputation: 41022
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:
Upvotes: 9
Reputation: 680
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
>
>
Upvotes: 3
Reputation: 101
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"}
Upvotes: 4
Reputation: 909
Many good tipps already, but the shortest and easiest (not necessarily the best) has yet to be mentioned:
object?
Upvotes: -2
Reputation: 2836
Try using:
print(object.stringify())
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__)
Upvotes: -4
Reputation: 811
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??
Upvotes: 3
Reputation: 19000
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.
Upvotes: 13
Reputation: 9285
import pprint
pprint.pprint(obj.__dict__)
or
pprint.pprint(vars(obj))
Upvotes: 2
Reputation: 25379
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.
Upvotes: 443
Reputation: 21382
Two great tools for inspecting code are:
IPython. A python terminal that allows you to inspect using tab completion.
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.
Upvotes: 5
Reputation: 1738
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
)
Upvotes: 15
Reputation: 19158
"""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__
Upvotes: 9
Reputation: 5546
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.
Upvotes: 27
Reputation: 16359
There is a python code library build just for this purpose: inspect Introduced in Python 2.7
Upvotes: 3
Reputation: 35247
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
>>>
Upvotes: 1
Reputation: 198867
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.
Upvotes: 93
Reputation: 3565
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.
Upvotes: 7
Reputation: 119371
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.
Upvotes: 31
Reputation: 87225
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__
Upvotes: 4
Reputation: 2393
In addition if you want to look inside list and dictionaries, you can use pprint()
Upvotes: 0
Reputation: 6904
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
Upvotes: 12