get the source code of a function in python using inspect
or the __source__
attribute
def function_code(fn):
""" returns the source code of the given function
by: Cody Kochmann
"""
from inspect import getsource
assert callable(fn), 'function_source needs its argument to be callable'
if '__source__' in dir(fn):
return fn.__source__
else:
try:
return getsource(fn)
except OSError:
return None