inspect.getsource returns unrelated code
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
The documentation of inspect.getsource states:
Return the text of the source code for an object. [...]
But the function returns slightly more code. It returns all lines of source code that overlap the object, even if the rest of the lines belong to different objects.
For example, the following code creates two lambdas in the same line, so inspect.getsource will return the code of both lambdas instead of just one.
import inspect
# Two function declarations in the same line
x = lambda: 1; y = lambda: 2
# prints "x = lambda: 1; y = lambda: 2\n"
print(repr(inspect.getsource(y)))
The returned code is not even necessarily valid Python, as the following list comprehension demonstrates:
import inspect
funcs = [
lambda: 1 for
_ in range(3)
]
# prints ' lambda: 1 for\n', including indentation and a stray "for"
print(repr(inspect.getsource(funcs[0])))
Background
I was trying to access the abstract syntax tree of a function (for JIT compilation), but that does not appear to be possible for lambdas.
Linked PRs
- gh-143301
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at inspect.getsource and reproduce the two examples from the issue, then inspect the surrounding implementation and existing tests for source extraction. Clarify the intended behavior for lambdas sharing a line or spanning comprehension syntax, and add regression coverage showing what should be returned. A linked pull request, gh-143301, indicates that work has already moved elsewhere.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100