2009
10.01

Python offers many built-in functions that makes it a language of choice for a lot of developer. We find it in many 3d packages like Softimage|XSI, Maya, Blender, Houdini, etc.

Sometime, rarely, some function might not be present from one language to the other. It’s actually the case with the JScript toString() function. There’s no simple/clean equivalent in Python. The missing behavior in Python is to be able to retreive the source code of a given function by calling it like in JScript: myFunc.toString(). It could be a built-in behavior like myFunc.__source__ (there’s actually some, but they don’t return what we are looking for).

Python can do it too, but with a bit more code. It has a built-in module called inspect. With this module we can retreive the source code of a given function (and much more) in a .py file. There’s one limitation with this method, it has to be in a file on the disk. It won’t work in a command line. Here’s an example of toString() written in Python:

def helloWorld():
    print('Eyyaa')
    return True

import inspect
source = inspect.getsourcelines(helloWorld)
for file in source:
    if getattr(file, '__iter__', False):
        for line in file:
            print(line)

The above solution as is isn’t really elegant like a simple toString() call to retreive the function source code, but well integrated in a module or a function/class, the result is the same. The down side of this code might be with the performance ( if it matters ).

1 comment so far

Add Your Comment