Get help from the marimo community

Updated 6 days ago

Inspect.getsource() for class throws OSError: could not find class definition

Plain Text
class Test():
   def __init__(self):
        self.a = 1
        self.b = 2 

import inspect

inspect.getsource(Test)


Traceback (most recent call last):
File "/Users/habib/.cache/uv/archive-v0/orE7lLvC9gKEvqF8RJqEB/lib/python3.12/site-packages/marimo/_runtime/executor.py", line 142, in execute_cell
return eval(cell.last_expr, glbls)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/var/folders/q1/7g9hgvc17m95t7yrvcclc75h0000gn/T/marimo_99501/marimocellZzoV.py", line 1, in <module>
inspect.getsource(Test)
File "/Users/habib/.local/share/uv/python/cpython-3.12.9-macos-aarch64-none/lib/python3.12/inspect.py", line 1285, in getsource
lines, lnum = getsourcelines(object)
^^^^^^^^^^^^^^^^^^^^^^
File "/Users/habib/.local/share/uv/python/cpython-3.12.9-macos-aarch64-none/lib/python3.12/inspect.py", line 1267, in getsourcelines
lines, lnum = findsource(object)
^^^^^^^^^^^^^^^^^^
File "/Users/habib/.local/share/uv/python/cpython-3.12.9-macos-aarch64-none/lib/python3.12/inspect.py", line 1112, in findsource
raise OSError('could not find class definition')
OSError: could not find class definition
C
H
3 comments
If you haven't defined the class in a file, then that's precisely the issue. The inspect.getsource() function works reliably when inspecting classes or functions defined in actual Python files, but struggles with objects defined in interactive environments.

The simplest solution is to define your Test class in a separate .py file, import it, and then use inspect.getsource() on the imported class.
Thank you for your response.
The interesting thing is that it works for functions but not for classes.

Yes, your solution works, but it's not appropriate for my use case.

I will go with reading the python file and use ast parser.

Before doing so I wanted to know if it is a known issue? should I open an Issue on github? because I want to make a jupyter library compatible for marimo and if this issue is fixable I would use inspect.getsource() instead of the ast parser.
using an ast parser instead of inspect.getsource() would be right approach for your cross compatible library. this is a known limitation in interactive environments where Python stores source information differently for classes versus functions. the issue isn't specific to marimo so maybe opening a github issue isn't necessary but if you want to dive deeper you can open an issue in github. your ast solution will work more reliably across jupyter, marimo and other interactive environments.
Add a reply
Sign up and join the conversation on Discord