Author terry.reedy
Recipients Claudiu.Popa, Ivan.Pozdeev, Naddiseo, Steven.Barker, eric.araujo, ned.deily, nikitakit, r.david.murray, terry.reedy, vmsp, zorceta
Date 2018-12-11.22:23:05
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1544566986.09.0.788709270274.issue12920@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2018-12-11 22:23:06terry.reedysetrecipients: + terry.reedy, ned.deily, eric.araujo, r.david.murray, Claudiu.Popa, Naddiseo, Steven.Barker, Ivan.Pozdeev, zorceta, nikitakit, vmsp
2018-12-11 22:23:06terry.reedysetmessageid: <1544566986.09.0.788709270274.issue12920@psf.upfronthosting.co.za>
2018-12-11 22:23:06terry.reedylinkissue12920 messages
2018-12-11 22:23:05terry.reedycreate