英文:
Get value and type of python variable similar to Jupyter behavior
问题
可以使用eval()
函数来获取最后一行表达式的值和类型。以下是在Python代码中实现的方法:
lines = """x = 1
y = x + 1
y"""
globals_dict = {}
locals_dict = {}
exec(lines, globals_dict, locals_dict)
result = eval(lines.split('\n')[-1], globals_dict, locals_dict)
result_type = type(result)
result_value = result
result_type, result_value
这将返回一个元组,其中包含最后一行表达式的类型和值,类似于 (int, 2)
,表示类型是整数,值为2。
英文:
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?
答案1
得分: 1
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.
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论