I am reading the book: “Obi Ike-Nwosu. Inside The Python Virtual Machine” and have reached the “Code Objects” chapter. This chapter has all code object fields printed out:
co_argcount = 1 co_cellvars = () co_code = b'|\x00d\x01\x16\x00d\x02k\x02r\x1e|\x00d\x03\x16\x00d\x02k\x02r\x1ed\ x04S\x00n,|\x00d\x01\x16\x00d\x02k\x02r0d\x05S\x00n\x1a|\x00d\x03\x16\x00d\x02k\x02r\ Bd\x06S\x00n\x08t\x00|\x00\x83\x01S\x00d\x00S\x00' co_consts = (None, 3, 0, 5, 'FizzBuzz', 'Fizz', 'Buzz') co_filename = /Users/c4obi/projects/python_source/cpython/fizzbuzz.py co_firstlineno = 6 co_flags = 67 etc...
but there is no explanation how this can be done programatically, so I wrote my own code:
# Making the code object for 'my_add' function code_obj = compile('my_add', os.path.realpath(__file__), 'exec') # Iterating through all instance attributes # and calling all having the 'co_' prefix for name in dir(code_obj): if name.startswith('co_'): co_field = getattr(code_obj, name) print(f'{name:<20} = {co_field}')
Output
co_argcount = 0 co_cellvars = () co_code = b'e\x00\x01\x00d\x00S\x00' co_consts = (None,) co_filename = /home/minimax/learning_python/oop/source.py co_firstlineno = 1 co_flags = 64 co_freevars = () co_kwonlyargcount = 0 co_lnotab = b'' co_name = <module> co_names = ('my_add',) co_nlocals = 0 co_stacksize = 1 co_varnames = ()
Question: Have I used the optimal way? How would you solve this problem?
EDIT
Additional information was discovered. It seems, that my solution is wrong. I have tried another approach (using my_add.__code__
) and got different code object field values, so I have asked the question on StackOverflow. Check it if you are interested.