Python 自省:return 函数参数作为字符串?

Python introspection: return function argument as a string?

这是我希望能够做的事情

x = 1

f(x+3) # returns 'x+3' (a string)

这可能吗?

(Lisp 和 C 可以做到这一点,但 f 必须是宏)

如果您要添加的值(3) 是常量,

`def f(x):
    return f"{x}+3"

f(x)

如果不是,可以传两个参数,

def f(x, y):
    return f"{x} + {y}"

f(x, y)


这是可能的,不管其他人怎么说。我能想到的唯一方法是检查源代码。我不建议在现实中这样做。不过,这是一个有趣的小玩具。

from inspect import currentframe
import linecache
import re

def f(x):

    cf = currentframe()
    calling_line_number = cf.f_back.f_lineno

    calling_line = linecache.getline(__file__, calling_line_number)
    m = re.search(r"^.*?f\((?P<arg>.*?)\).*$", calling_line)
    if m:
        print (m.group("arg"))

x = 1
f(x + 3)

打印 x + 3,这正是传递给 f() 的内容。