Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Instrospection: get source of the cell from the cell ? #213

Open
paugier opened this issue Dec 2, 2024 · 2 comments
Open

Instrospection: get source of the cell from the cell ? #213

paugier opened this issue Dec 2, 2024 · 2 comments

Comments

@paugier
Copy link

paugier commented Dec 2, 2024

When executing a notebook with nbval, get_ipython().history_manager.input_hist_raw (mentioned by @takluyver in jupyter/notebook#3101 (comment)) does not work for recent versions of nbval, so it is not possible to get the source of a cell from a cell.

I used this feature in https://transonic.readthedocs.io and I test it with nbval~=0.9.6.

Is it possible to get the cell input in Python from the cell with recent version of nbval ?

@takluyver
Copy link
Member

Probably from #190, making nbval not store every cell it runs into your IPython history database.

I think this is another option that probably still works:

import sys, linecache

linecache.getlines(sys._getframe().f_code.co_filename)

But this is all a bunch of implementation details, so don't be too surprised if that one day stops working as well. If you want a stable API to get the code cell currently running, that would be up to IPython or ipykernel - but I think it's a pretty niche request.

@takluyver
Copy link
Member

(Oh, and in case it's not obvious, the sys._getframe() thing needs to be directly in a code cell, not wrapped in a function. You could walk the stack from inside a function to get back to the code cell, if you need to, but it's going to get fiddly.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants