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


Groups > comp.lang.python > #76631

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

From Ben Finney <ben+python@benfinney.id.au>
Subject Re: why i can't get the sourcecode with inspect module?
Date 2014-08-20 13:21 +1000
References <53F41076.8010508@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.13187.1408504921.18130.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

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

csiph-web