Josh Gibson
Josh Gibson

Reputation: 22908

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 lets me do stuff like

MyCls??

And it will show me the source.

Upvotes: 5

Views: 255

Answers (4)

Alex Martelli
Alex Martelli

Reputation: 881527

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

Upvotes: 2

Ned Batchelder
Ned Batchelder

Reputation: 375484

The inspect module has everything you need.

Upvotes: 2

Lukáš Lalinský
Lukáš Lalinský

Reputation: 41306

sys.modules[MyCls.__module__].__file__

or

inspect.getsourcefile(MyCls)

There are more __xxx__ attributes on various objects you might find useful.

Upvotes: 8

Amber
Amber

Reputation: 526543

Here's a pretty good overview of many of Python's meta-info capabilities:

http://www.ibm.com/developerworks/library/l-pyint.html

Upvotes: 4

Related Questions