使用inspect.getsource()获取自定义类定义时报错,如何解决?
解决inspect.getsource()获取交互式环境定义类的报错问题
错误原因:你在交互式环境(比如Jupyter Notebook/IPython)中定义的类,代码仅存于内存,没有对应的磁盘源文件。inspect.getsource()依赖读取磁盘上的源代码文件来获取类定义,因此会误将其识别为“内置类”抛出错误。
正确解决方法
方法1:将类定义保存到.py文件中(推荐)
- 创建名为
myclass.py的文件,写入类定义:
class MyFirstClass: pass
- 在脚本或交互式环境中导入该类并调用
inspect.getsource():
import inspect from myclass import MyFirstClass print(inspect.getsource(MyFirstClass))
执行后会得到预期输出:
class MyFirstClass: pass
方法2:交互式环境下的替代方案(针对Jupyter/IPython)
如果必须在交互式环境中操作,可使用IPython自带的getsource方法:
from IPython.core.getipython import get_ipython ip = get_ipython() print(ip.magics_manager.lsmagic()['line']['getsource']('MyFirstClass'))
也可以使用dill库(需先执行pip install dill安装):
import dill print(dill.source.getsource(MyFirstClass))
内容的提问来源于stack exchange,提问作者vasili111
相关产品推荐
相关产品推荐

