Get "code object" of class

Matimus mccredie at gmail.com
Fri Oct 10 14:04:06 EDT 2008


On Oct 10, 5:50 am, Okko Willeboordse <tr... at willeboordse.demon.nl>
wrote:
> To get the "code object" c of my_class I can do;
>
> c = compile(inspect.getsource(my_class), "<script>", "exec")
>
> This fails when inspect can't get hold of the source of my_class,
> for instance when my_class is in a pyc file.
>
> Is there another way of getting c?

Classes don't have a code object that is visible at run-time, at least
not that I know of. The class body is executed when the class is
created and then discarded. _Most_ of the time classes are created at
the module level. However, when a module is compiled, the class does
have a code object which is marshaled and placed inside of the
compiled code. If anybody knows of a simpler way, I would be
interested, but here is _one_ way you can get at the code object if
the class is in a compiled module:

>>> f = open("testclass.pyc", "rb")
>>> import marshal
>>> f.seek(8)
>>> o = marshal.load(f)
>>> o
<code object <module> at 00D81DA0, file "testclass.py", line 2>
>>> dir(o)
['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__',
'__hash__
', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr_
_', '__str__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts',
'co_filenam
e', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab',
'co_name', 'co_nam
es', 'co_nlocals', 'co_stacksize', 'co_varnames']
>>> o.co_consts
('CBase', <code object CBase at 00D81578, file "testclass.py", line
2>, 'C', <co
de object C at 00D81380, file "testclass.py", line 11>, 'D', <code
object D at 0
0D81530, file "testclass.py", line 15>, None)
>>> # Get the code object for class 'C'
>>> code_obj = o.co_consts[3]

I wouldn't recommend doing it this way though. It is very convoluted
and since the 'dir' method sometimes hides some of the attributes, I
wouldn't be surprised if the code object _was_ available and I just
don't know the name. Why do you even need the classes code object
anyway?

Matt



More information about the Python-list mailing list