Search code examples
pythoncompilationcpythonpython-internals

What is the type of Python's code object?


Is there a way I can compare to the type of a code object constructed by compile or __code__ to the actual code object type?

This works fine:

>>> code_obj = compile("print('foo')", '<string>', 'exec')
>>> code_obj
<code object <module> at 0x7fb038c1ab70, file "<string>", line 1>
>>> print(type(code_obj))
code
>>> def foo(): return None
>>> type(foo.__code__) == type(code_obj)
True

But I can't do this:

>>> type(foo.__code__) == code
NameError: name 'code' is not defined

but where do I import code from?

It doesn't seem to be from code.py. It's defined in the CPython C file but I couldn't find the Python interface type for it.


Solution

  • You're after CodeType which can be found in types.

    >>> from types import CodeType
    >>> def foo(): pass
    ... 
    >>> type(foo.__code__) == CodeType
    True
    

    Note that there's nothing special about it, it just uses type on a functions __code__.

    Since it's in the standard lib, you can be sure it will work even if some change happens in the way code objects are exposed.