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 wo
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
>>>
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__)
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.
import pprint
pprint.pprint(obj.__dict__)
or
pprint.pprint(vars(obj))
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??
object.__dict__