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
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.
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.
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 .
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With