New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
inconsistent results with inspect.getsource / .getsourcelines #66551
Comments
The functions inspect.getsource() and inspect.getsourcelines() return inconsistent results for frames corresponding to class definitions within a function. Test code: import sys
import inspect
def case1():
class C:
def __init__(self):
pass
c = C()
def case2():
a = 1
class C:
def __init__(self):
pass
c = C()
def case3():
def fn():
pass
class C:
def __init__(self):
pass
c = C()
def trace(frame,event,arg):
code = frame.f_code
print('name:',code.co_name)
print('source:\n',inspect.getsource(code),'\n')
for case in ('case1','case2','case3'):
print('#####',case)
call = getattr(sys.modules[__name__],case)
sys.settrace(trace)
try:
call()
finally:
sys.settrace(None) Result: ##### case1 name: C name: __init__ ##### case2 name: C name: __init__ ##### case3 name: C name: __init__ The source listed for frames named 'C' (the class creation code) is not consistent across all three cases. It could be considered incorrect in all cases as it does not correspond only to the class definition source lines. |
Possible fix: --- /usr/lib64/python3.3/inspect.py 2014-06-30 19:21:52.000000000 +0200
+++ inspect.py 2014-09-07 17:41:29.463936079 +0200
@@ -600,7 +600,8 @@
if not hasattr(object, 'co_firstlineno'):
raise IOError('could not find function definition')
lnum = object.co_firstlineno - 1
- pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
+ pat = re.compile(
+ r'^(\s*(?:def|class)\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
while lnum > 0:
if pat.match(lines[lnum]): break
lnum = lnum - 1 |
I think this issue is covered with bpo-35101. It has an open PR as per the proposed fix with tests : https://github.com/python/cpython/pull/10209/files |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: