Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Get source code of class (using inspect)

I am using ipython and I want to save a class defined in one of my notebooks. I can do this with functions nicely with %save and inspect.getsource, but I cant seem to get the source of my class. I had a quick look at the methods in inspect and couldnt seem to find anything that could help. Any suggestions?

class A():
    def __init__(self):
        self.x = 1

%save filename.py inspect.getsource(A)

inspect.getsource(A)
>>> ...
>>> TypeError: <module '__main__'> is a built-in class
like image 838
Alexander Telfar Avatar asked Mar 07 '16 21:03

Alexander Telfar


People also ask

How do you inspect a class in Python?

Methods to verify the type of token: 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.

Can Python view source code?

To view the source you can open a . py file with IDLE (which comes with Python) or even Notepad although a more advanced text editor or IDE is recommended. See Is there a good, free Python IDE for Windows for IDE recommendations by the stackoverflow community.

How do you find the source code of a built in function in Python?

Since Python is open source you can read the source code. To find out what file a particular module or function is implemented in you can usually print the __file__ attribute. Alternatively, you may use the inspect module, see the section Retrieving Source Code in the documentation of inspect .

What is inspect stack ()?

inspect. stack() returns a list with frame records. In function whoami() : inspect. stack()[1] is the frame record of the function that calls whoami , like foo() and bar() . The fourth element of the frame record ( inspect.


1 Answers

getsource works by actually opening the source file that defines the object you're looking at.

But, since you defined A in the interactive interpreter, there is no such source file, and therefore Python can't find one.

The error is somewhat obscure, but Python basically tries to look up the source file for A's module (A.__module__), which is __main__, and which has no __file__ property (because it didn't come from a file).

like image 140
Thomas Orozco Avatar answered Sep 29 '22 22:09

Thomas Orozco