Given a Python class, how can I inspect and find the place in my code where it is defined?
I'm building a debugging tool.
IPython le开发者_开发知识库ts me do stuff like
MyCls??
And it will show me the source.
sys.modules[MyCls.__module__].__file__
or
inspect.getsourcefile(MyCls)
There are more __xxx__
attributes on various objects you might find useful.
Here's a pretty good overview of many of Python's meta-info capabilities:
http://www.ibm.com/developerworks/library/l-pyint.html
The inspect module has everything you need.
If you just want to see the source, inspect.getsource is a very direct way to do that; for more advanced uses (getting the source file, line numbers, etc), see other functions in inspect
documented at the same URL just before getsource
. Note that each such function will raise an exception if source is not available, so make sure to be within a try
/except
block when you call it, and handle the exception as appropriate for your case. (Also, as I might hope goes without saying, you do need to import inspect
in your modules in which you want to call inspect
functionality).
精彩评论