0

I came across this interesting fact and I am wondering how to come over it. By using inspect it is easy to get the source code of a lambda. But as soon as you return the very same lambda from an eval statement the get source function fails.

import inspect

f = lambda a: a*2
f2 = eval("lambda a: a*2")

inspect.getsource(f), inspect.getsource(f2)


/usr/lib/python3.7/inspect.py in getsource(object)
    971     or code object.  The source code is returned as a single string.  An
    972     OSError is raised if the source code cannot be retrieved."""
--> 973     lines, lnum = getsourcelines(object)
    974     return ''.join(lines)
    975 

/usr/lib/python3.7/inspect.py in getsourcelines(object)
    953     raised if the source code cannot be retrieved."""
    954     object = unwrap(object)
--> 955     lines, lnum = findsource(object)
    956 
    957     if istraceback(object):

/usr/lib/python3.7/inspect.py in findsource(object)
    784         lines = linecache.getlines(file)
    785     if not lines:
--> 786         raise OSError('could not get source code')
    787 
    788     if ismodule(object):

OSError: could not get source code

Is there a way to come over this and get the source of evaluated code?

KIC
  • 5,887
  • 7
  • 58
  • 98
  • 1
    Functions don't remember their source code - all they know is the filename and line numbers they came from. If the function definition wasn't in a physical file that is still available, then it is *utterly impossible* for `inspect.getsource()` to work. You'd need a decompiler, instead. – jasonharper May 08 '20 at 13:55
  • Ok makes sense. How could I do a check if a file is available? something like func.parent.__file__. PS you might also add this as an answer. – KIC May 08 '20 at 14:19
  • The simplest solution would be to call `inspect.getsource()` and catch the exception it throws if the file is unavailable. But I have to wonder if you should be going down this path at all - `inspect` is for debugging, not something you should rely on for normal functioning of a program. – jasonharper May 08 '20 at 14:21
  • it is part of an exception handler where one passes a lamba to a function. it is just convenient for exactly debugging. – KIC May 08 '20 at 14:27

1 Answers1

2

Functions don't remember their source code - all they know is the filename and line numbers they came from. If the function definition wasn't in a physical file that is still available, then it is utterly impossible for inspect.getsource() to work. You'd need a decompiler, instead.

thx, jasonharper

KIC
  • 5,887
  • 7
  • 58
  • 98
  • Where is that written? – not2qubit Jan 15 '22 at 14:19
  • [Here](https://stackoverflow.com/a/55386046/1147688) and [here](https://stackoverflow.com/questions/62160529/how-to-get-source-inside-exec-python) are some other good and related answers. – not2qubit Jan 16 '22 at 11:50