Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a Python class, how can I inspect and find the place in my code where it is defined?

Tags:

python

I'm building a debugging tool.

IPython lets me do stuff like

MyCls??

And it will show me the source.

like image 882
Josh Gibson Avatar asked Oct 14 '09 19:10

Josh Gibson


People also ask

How do you inspect a class in Python?

isclass(): The isclass() method returns True if that object is a class or false otherwise. When it is combined with the getmembers() functions it shows the class and its type. It is used to inspect live classes.

How do you inspect code in Python?

We use the getsource() method of inspect module to get the source code of the function. Returns 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.

How do you find the details of an object in Python?

To list all the attributes of an object, use the built-in dir() function. It returns a long list of attribute names, that is, method and variable names of the object. There is a bunch of automatically generated attributes in any Python class.


1 Answers

sys.modules[MyCls.__module__].__file__

or

inspect.getsourcefile(MyCls)

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

like image 87
Lukáš Lalinský Avatar answered Oct 04 '22 01:10

Lukáš Lalinský