You cannot do this in the regular console. iPython keeps a copy of the source in case you want to see it again later on, but the standard Python console does not.
Had you imported the function from a file, you could have used inspect.getsource()
:
>>> import os.path
>>> import inspect
>>> print inspect.getsource(os.path.join)
def join(a, *p):
"""Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded. An empty last part will result in a path that
ends with a separator."""
path = a
for b in p:
if b.startswith('/'):
path = b
elif path == '' or path.endswith('/'):
path += b
else:
path += '/' + b
return path
but, just to be explicit, inspect.getsource()
will fail for functions entered in the interactive console:
>>> def foo(): pass
...
>>> print inspect.getsource(foo)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/inspect.py", line 701, in getsource
lines, lnum = getsourcelines(object)
File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/inspect.py", line 690, in getsourcelines
lines, lnum = findsource(object)
File "/Users/mj/Development/Libraries/buildout.python/parts/opt/lib/python2.7/inspect.py", line 538, in findsource
raise IOError('could not get source code')
IOError: could not get source code
because nothing in the interpreter retains the input (other than the readline library, which might save input history, just not in a format directly usable by inspect.getsource()
).