获取Python变量的值和类型,类似Jupyter的行为。

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月7日 02:55:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654750.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定