Question

I found code objects in Python. I'm curious as to what each of the variables in the constructors do. There is not much information on them in the builtin help function all I got was:

 class code(object)
 |  code(argcount, nlocals, stacksize, flags, codestring, constants, names,
 |        varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]])
 |  
 |  Create a code object.  Not for the faint of heart.

That is obviously not very informative. What types do each of these inputs expect, and what do the values do? NOTE: I asked this question out of academic curiosity, and not for any specific coding purpose.

Was it helpful?

Solution

A Python code object is mostly just a container for its attributes. Each of the arguments you see for the constructor becomes an attribute with a co_ prefix (e.g. the argcount argument becomes the co_argcount attribute).

The constructor does do a bit of validation, so if the arguments are not of the right type, it will raise an exception right away (rather than only failing when the code object is used later on).

As for what the arguments and attributes mean, that's mostly documented in a big table in the documentation for the inspect module. Here's the relevant part:

code  co_argcount     number of arguments (not including * or ** args)   
      co_code         string of raw compiled bytecode    
      co_consts       tuple of constants used in the bytecode    
      co_filename     name of file in which this code object was created     
      co_firstlineno  number of first line in Python source code     
      co_flags        bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg   
      co_lnotab       encoded mapping of line numbers to bytecode indices    
      co_name         name with which this code object was defined   
      co_names        tuple of names of local variables      
      co_nlocals      number of local variables      
      co_stacksize    virtual machine stack space required   
      co_varnames     tuple of names of arguments and local variables

The attributes co_freevars and co_cellvars are not documented as far as I can see. They're related to closures, I think.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top