Search code examples
pythonjupyter-notebookjupyterjupyter-lab

Get value and type of python variable similar to Jupyter behavior


Assume you have a Jupyter notebook with one entry that has three lines:

x = 1
y = x + 1
y

The output will print '2'

I want to do this inside my python code. If I have a variable lines and run exec:

 lines = """x = 1
            y = x + 1
            y"""

 exec(lines,globals(),locals())

I will not get any result, because exec returns None. Is there a way to obtain the value and type of the expression in the last line, inside a python program?


Solution

  • After your exec add a print() of the eval() of the last line to get the value, like so:

    lines = """x = 1
    y = x + 1
    y"""
    
    exec(lines,globals(),locals())
    print(eval(lines.split("\n")[-1]))
    

    Then to add in the type(), you add in running the type on that eval() to then get the value and type shown:

    lines = """x = 1
    y = x + 1
    y"""
    
    exec(lines,globals(),locals())
    print(eval(lines.split('\n')[-1]),"          type: {}".format(type(eval(lines.split('\n')[-1])))) # I put the
    # last line code into string format with `.format()` because f-string didn't like the `\n`, see https://stackoverflow.com/q/51775950/8508004
    

    Be cautious when using exec() and eval(). See paragraph starting 'Keep in mind that use of exec()..' here and links therein.