Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #76631 > unrolled thread

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

Started byBen Finney <ben+python@benfinney.id.au>
First post2014-08-20 13:21 +1000
Last post2014-08-20 13:21 +1000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: why i can't get the sourcecode with inspect module? Ben Finney <ben+python@benfinney.id.au> - 2014-08-20 13:21 +1000

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

FromBen Finney <ben+python@benfinney.id.au>
Date2014-08-20 13:21 +1000
SubjectRe: why i can't get the sourcecode with inspect module?
Message-ID<mailman.13187.1408504921.18130.python-list@python.org>
luofeiyu <elearn2014@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web