Quantcast
Channel: Print all variables defined in one Jupyter cell - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by BenedictWilkins for Print all variables defined in one Jupyter cell

$
0
0

So, this was a tough nut to crack. Essentially we are just trying to grab all of the lines in the current cell and extract the variables. As it turns out, we cannot use the global variables defined by IPython (e.g. _, __, _i<n> etc) as suggested in Programmatically get current Ipython notebook cell output? because (as far as my experiments have shown) you can only grab values from previously executed cells and not the one currently being executed.

Luckily for us, it turns out that using the magic command %historydoes grab the input of the current cell. So with the help of this and this I have created a function that does exactly what you want:

def cell_vars(offset=0):    import io    from contextlib import redirect_stdout    ipy = get_ipython()    out = io.StringIO()    with redirect_stdout(out):        ipy.magic("history {0}".format(ipy.execution_count - offset))    #process each line...    x = out.getvalue().replace("", "").split("\n")    x = [a.split("=")[0] for a in x if "=" in a] #all of the variables in the cell    g = globals()    result = {k:g[k] for k in x if k in g}    return result

You can test it with something like:

a = 1b = 2c = 3cell_vars()

which should give {'a': 1, 'b': 2, 'c': 3}, you can then format this and print it however you like. Obviously there are some limitations with my line processing (assumes that all variables of interest are in global scope).

Hope this is useful!


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>