3 ms·
It's not that straightforward under the hood. Python doesn't keep an object's source code around. inspect.getsource(func) uses func.__code__.co_filename and fu
by duckerude 6y ago
It's not that straightforward under the hood. Python doesn't keep an object's source code around.
inspect.getsource(func) uses func.__code__.co_filename and func.__code__.co_firstlineno to figure out where the definition of func starts, runs that part of the file through a tokenizer, and uses heuristics to guess where the definition stops.
Sometimes it guesses wrong, particularly if lambdas are involved. Sometimes the code moved around in the meantime. Sometimes the code never even existed on disk, for example because it was entered into a REPL.
That's what they mean by "reconstitute the Python source".
- tom_mellior 6y agoThanks. I know I have used this decorator approach in the past to grab the ASTs for Python functions, but I guess my scenarios were all on the happy path. I see now where this might not be bulletproof.