Search code examples
pythonpython-3.xmetaprogrammingintrospection

Python introspection: return function argument as a string?


Here is what I'd like to be able to do

x = 1

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

Is this possible?

(Lisp and C can do this, but f would have to be a macro)


Solution

  • This is possible, despite what others have said. The only way I can think of to do this is to inspect the source code. I cannot recommend doing this in reality. It's a fun little toy, though.

    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)
    

    Prints x + 3, which is exactly what was passed to f().