Terry J. Reedy <tjre...@udel.edu> added the comment:

Do we really need to say that getsource(object) can only get the object's 
source if it is accessible from the object?  Getsource also fails if a module 
is loaded from a .pyc with not corresponding .py available.

The problem is not the call being in __main__.  When I put the three lines 
(with the 3rd wrapped with print()) in an IDLE editor and run, and re-inspect, 
I get

======================== RESTART: F:\Python\a\tem3.py ========================
class A:
    pass

>>> inspect.getsource(A)
'class A:\n    pass\n'

Ditto if I run > py -i -m a.tem3

If I continue in IDLE's Shell

>>> class B: pass

>>> inspect.getsource(B)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    inspect.getsource(B)
  File "F:\dev\37\lib\inspect.py", line 973, in getsource
    lines, lnum = getsourcelines(object)
  File "F:\dev\37\lib\inspect.py", line 955, in getsourcelines
    lines, lnum = findsource(object)
  File "F:\dev\37\lib\inspect.py", line 812, in findsource
    raise OSError('could not find class definition')
OSError: could not find class definition

If I enter the three lines above in a fress python or IDLEs shell, I get the 
TypeError above.

IDLE does store interactive inputs into linecache, so that tracebacks contain 
the offending line (unlike interactive python). But it does so on a statement 
by statement basis, so that each entry is treated as a separate file.  In a 
traceback for an exception in a multiline statement, the line number is 
relative to the statement.

>>> def f():
        # line2 of f
        1/0

        
>>> f()
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    f()
  File "<pyshell#12>", line 3, in f
    1/0
ZeroDivisionError: division by zero

Interactive python displays '<stdin>' as the file for all entries.  IDLE 
numbers them, so previous statements remained cached.  I consider enhanced 
interactive tracebacks to be an important feature.

But I don't see how to attach individual pseudofile names to classes and 
functions so that getsource could find their source lines.

----------
nosy: +terry.reedy
versions: +Python 3.7, Python 3.8 -Python 2.7, Python 3.4, Python 3.5, Python 
3.6

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue12920>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to