why i can't get the sourcecode with inspect module?

2014-08-19 Thread luofeiyu

 import inspect
 def changer(x,y):
... return(x+y)
...
 dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__
 'changer', 'inspect']
 inspect.getsource(changer)
Traceback (most recent call last):
  File stdin, line 1, in module
  File D:\Python34\lib\inspect.py, line 830, in getsource
lines, lnum = getsourcelines(object)
  File D:\Python34\lib\inspect.py, line 819, in getsourcelines
lines, lnum = findsource(object)
  File D:\Python34\lib\inspect.py, line 667, in findsource
raise OSError('could not get source code')
OSError: could not get source code

--
https://mail.python.org/mailman/listinfo/python-list


Re: why i can't get the sourcecode with inspect module?

2014-08-19 Thread Ben Finney
luofeiyu elearn2...@gmail.com writes:

  import inspect
  def changer(x,y):
 ... return(x+y)
 ...

At this point, you have defined a function. It is accessible via the
‘changer’ name, and the code is available.

But the source code is not available; Python reads standard input but
doesn't preserve it.

  dir()
 ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__
  'changer', 'inspect']

I don't know what this is meant to demonstrate.

Maybe ‘dir(changer.__code__)’ would be instructive.

  inspect.getsource(changer)
 Traceback (most recent call last):
   File stdin, line 1, in module
   File D:\Python34\lib\inspect.py, line 830, in getsource
 lines, lnum = getsourcelines(object)
   File D:\Python34\lib\inspect.py, line 819, in getsourcelines
 lines, lnum = findsource(object)
   File D:\Python34\lib\inspect.py, line 667, in findsource
 raise OSError('could not get source code')
 OSError: could not get source code
 

Exactly. The ‘inspect.getsource’ function gets the source code, if it's
available. The source code doesn't exist any more, so it's not
available; an OSError is raised.

-- 
 \ “You say I took the name in vain / I don't even know the name / |
  `\But if I did, well, really, what's it to you?” —Leonard Cohen, |
_o__) _Hallelujah_ |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why i can't get the sourcecode with inspect module?

2014-08-19 Thread Steven D'Aprano
On Wed, 20 Aug 2014 11:05:26 +0800, luofeiyu wrote:

 import inspect
   def changer(x,y):
 ... return(x+y)


The interactive interpreter doesn't store the source code you type. It 
compiles it to byte-code, executes the byte-code, and throws the source 
code away.


-- 
Steven
-- 
https://mail.python.org/mailman/listinfo/python-list