Search code examples
pythonironpythonintrospection

IronPython getting function code as string at runtime


i am implementing a function framework in python to be accessed from C#.

As a requirement, i have to provide a "string representation" of the function at runtime.

Is there a way to get the code definition of a function as a string? something like:

def sum(a,b): 
    return a + b

def ToString(sum):
    # would return "def sum(a,b): return a+b" or something alike.

Thank you very much!


Solution

  • The function you are looking for is inspect.getsource(). Note that it will only work if the source file is accessible, so it won't work in the interactive console.