I have found a bug in inspect.getsource. I am using Python 2.2.2 on Red-Hat 7.3. Here is the problem. --begin bug.py import inspect def f(x): return x print inspect.getsource(f) --end bug.py % python bug.py Traceback (most recent call last): File "bug.py", line 3, in ? print inspect.getsource(f) File "/usr/local/lib/python2.2/inspect.py", line 520, in getsource return string.join(lines, '') File "/usr/local/lib/python2.2/string.py", line 131, in join return sep.join(words) TypeError: sequence expected, NoneType found Notice that --begin noproblem.py import inspect def f(x): return x print inspect.getsource(f) --end noproblem.py works: % python noproblem.py def f(x): return x I discovered this bug in trying to retrieve the source code for lambda expressions: --begin lambda.py import inspect f=lambda x: x print inspect.getsource(f) --begin lambda.py (same error message). -- Michele Simionato - Dept. of Physics and Astronomy 210 Allen Hall Pittsburgh PA 15260 U.S.A. Phone: 001-412-624-9041 Fax: 001-412-624-9163 Home-page: http://www.phyast.pitt.edu/~micheles/
Logged In: YES user_id=92689 It seems inspect.py indeed has problems finding one-line functions. I've attached a patch that addresses this, but to also make it work for lambda's I had to remove a few lines that I don't quite understand the purpose of, as it seems to work well without it. I've commented them out. Their purpose seems to be to adjust co.co_firstlineno in case it's off, it's just that I don't know how/when it can be off.
Logged In: YES user_id=80475 I made my own cut at this and also found that the problem was the try/except fall-through returning None instead of the first line. Also, I've added 'lambda' to regular expression search so that lambda's work as well as defs. The part that jvr commented out needs to stay in. It starts at the first line of code and works its way back until the def is found, that way the comments and docstring get included. Since Just and I independently arrived at the same analysis, considering this one solved. Committed as Lib/inspect.py 1.40 Not recommending for backport because handling one liners is more featuresque than buglike.