Get value and type of python variable similar to Jupyter behavior

Question:

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?

Asked By: ps0604

||

Answers:

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[-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[-1]),f"          type: {type(eval(lines[-1]))}")

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

Answered By: Wayne