Finding source from class or instance?

Michael Hudson mwh21 at cam.ac.uk
Sat Jan 20 14:17:14 EST 2001


Moshe Zadka <moshez at zadka.site.co.il> writes:

> On Thu, 18 Jan 2001 10:42:32 +0100, "Alex Martelli" <aleaxit at yahoo.com> wrote:
> 
> > There is a dis module, that does 'disassembly' of bytecode, but
> > that's lower-level than the Python source you seek, and also
> > seems to apply only to _methods_ defined in a class rather than
> > to the code in the classbody itself (offhand, I don't know how
> > to get to the codeobject for the latter -- anybody...?).
> 
> AFAIK, you can't. The code is executed, and then forgotten.

It'll be in the co_consts for the code that executed the class
statement, I think, but that may be less than trivial to get at too.

E.g.

$ cat a.py
class A:
 def __init__(self):
  print 1
$ python
[...]
>>> f=open("a.pyc")
>>> f.seek(8)
>>> c=marshal.load(f)
>>> c.co_consts 
('A', <code object A at 0x8174668, file "a.py", line 1>, None)
>>> c.co_consts[1]
<code object A at 0x8174668, file "a.py", line 1>
>>> 

Cheers,
M.

-- 
  Programming languages should be designed not by piling feature on
  top of  feature, but by removing the  weaknesses and restrictions
  that make the additional features appear necessary.
               -- Revised(5) Report on the Algorithmic Language Scheme



More information about the Python-list mailing list