Inspect Code Object Metadata
Core idea
A code object stores compiled instructions and metadata, not a function’s live globals or closure values. Function objects combine code with an execution environment. co_consts describes embedded constants, co_varnames local slots, and co_freevars captured names. These are introspection fields, not a stable bytecode serialization contract.
def fee(units): result = units * 4 return resultc = fee.__code__print(c.co_argcount, c.co_varnames)print(4 in c.co_consts)The code knows argument and local names; it does not hold a particular call’s units.
Expected output:
1 ('units', 'result')TrueCompare shared code and closure values
def factory(rate): def charge(n): return rate*n return chargea, b = factory(2), factory(5)print(a.__code__ is b.__code__)print(a.__code__.co_freevars, a(3), b(3))Both functions use the same compiled body but carry different closure cells.
Expected output:
True('rate',) 6 15Common mistake
Do not construct or modify raw code objects to change a function casually. Their fields and instruction encodings have version-specific constraints; use source-level functions instead.
Practice
Inspect co_names, co_consts and co_freevars of a function that uses a global and a captured variable. Compare code and closure metadata.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Code objects
Check your understanding of code objects.
What is printed?
def f(x,y): return x+yprint(f.__code__.co_argcount)What is printed?
def f(): return 9print(9 in f.__code__.co_consts)Where are captured runtime values kept?
Does a code object alone contain the function globals mapping?