Prev: Why 'open' is not a function according to inspect module?
Next: print line number and source filename
From: Peng Yu on 22 Jun 2010 11:53 Hi, It seems I don't completely understand how getsource works, as I expect that I should get the source code of class A. But I don't. Would you please let me know what I am wrong? $ cat main.py #!/usr/bin/env python import inspect class A: pass a=A() print inspect.getsource(a) $ ./main.py Traceback (most recent call last): File "./main.py", line 10, in <module> print inspect.getsource(a) File "/home/pengy/utility/linux/opt/Python-2.6.5/lib/python2.6/inspect.py", line 689, in getsource lines, lnum = getsourcelines(object) File "/home/pengy/utility/linux/opt/Python-2.6.5/lib/python2.6/inspect.py", line 678, in getsourcelines lines, lnum = findsource(object) File "/home/pengy/utility/linux/opt/Python-2.6.5/lib/python2.6/inspect.py", line 519, in findsource file = getsourcefile(object) or getfile(object) File "/home/pengy/utility/linux/opt/Python-2.6.5/lib/python2.6/inspect.py", line 441, in getsourcefile filename = getfile(object) File "/home/pengy/utility/linux/opt/Python-2.6.5/lib/python2.6/inspect.py", line 418, in getfile raise TypeError('arg is not a module, class, method, ' TypeError: arg is not a module, class, method, function, traceback, frame, or code object -- Regards, Peng
From: James Mills on 22 Jun 2010 12:00 On Wed, Jun 23, 2010 at 1:53 AM, Peng Yu <pengyu.ut(a)gmail.com> wrote: > It seems I don't completely understand how getsource works, as I > expect that I should get the source code of class A. But I don't. > Would you please let me know what I am wrong? If you "read" the documentation carefully: """ getsource(object) Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An IOError is raised if the source code cannot be retrieved. """ This "does not" include an object / instance (whichever you prefer). $ python main.py class A: pass $ cat main.py import inspect class A: pass a=A() print inspect.getsource(a.__class__) cheers James -- -- -- "Problems are solved by method"
From: Ian Kelly on 22 Jun 2010 12:01
On Tue, Jun 22, 2010 at 9:53 AM, Peng Yu <pengyu.ut(a)gmail.com> wrote: > Hi, > > It seems I don't completely understand how getsource works, as I > expect that I should get the source code of class A. But I don't. > Would you please let me know what I am wrong? > > $ cat main.py > #!/usr/bin/env python > > import inspect > > class A: > pass > > a=A() > > print inspect.getsource(a) You passed in an instance of the class, not the class itself. The following will work: print inspect.getsource(A) As will: print inspect.getsource(a.__class__) Cheers, Ian |