Skip to content

code objects: missing attributes #1838

Closed

Description

@ep12

Feature

code objects do not have the following attributes

Maybe it does not make sense to implement the last two or three items (as far as I know the bytecode is not cpython compatible?). But the other ones can be implemented, I think.
I wish I'd be able to do that, but the only language I really speak is python 😞.

Example

# cpython 3.8
import inspect
from pprint import pprint

def code_info(code): 
    return {(k1:=f'co_{k}'): getattr(code, k1) for k in ('names', 'varnames', 'cellvars', 'freevars')}

def foo(arg1, arg2=None): 
    x_foo = 42 
    def bar(arg_bar): 
        x_bar = 73 
        return arg_bar * x_bar, x_foo, arg2 
    return bar, inspect.currentframe()

bar_func, f = foo(1)
pprint(code_info(f.f_code))
pprint(code_info(bar_func.__code__))

should print

{'co_names': ('inspect', 'currentframe'),
 'co_varnames': ('arg1', 'arg2', 'bar'),
 'co_cellvars': ('arg2', 'x_foo'),
 'co_freevars': ()}
{'co_names': (),
 'co_varnames': ('arg_bar', 'x_bar'),
 'co_cellvars': (),
 'co_freevars': ('arg2', 'x_foo')}

Note that with #1834 f.f_code.co_varnames is ('arg1', 'arg2') (bar missing) and bar_func.__code__.co_varnames is ('arg_bar',) (x_bar missing).

Python Documentation

cpython source code

Activity

  1. added
    C-compatA discrepancy between RustPython and CPython
    on Apr 3, 2020
  2. ep12 commented on Apr 3, 2020

    @ep12
    Author

    Maybe also related: #1327

  3. self-assigned this
    on Dec 21, 2020
  4. coolreader18 commented on Dec 21, 2020

    @coolreader18
    Member

    This should be doable now that #2355 is merged, and the co_stacksize property can be added to #2373.

  5. youknowone commented on Oct 6, 2026

    @youknowone
    Member

    The originally missing code attributes are present on current main: co_varnames, co_names, co_cellvars, co_freevars, co_nlocals, co_stacksize, and co_code. co_lnotab is gone in 3.14 in favor of co_linetable, which exists. Closing.

    — commented by Grok 4.6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

A-stdlibC-compatA discrepancy between RustPython and CPython

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions