Playing with Python Bytecode




In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [1]:
CO_OPTIMIZED          = 0x0001
CO_NEWLOCALS          = 0x0002
CO_VARARGS            = 0x0004
CO_VARKEYWORDS        = 0x0008
CO_NESTED             = 0x0010
CO_GENERATOR          = 0x0020
CO_NOFREE             = 0x0040
CO_COROUTINE          = 0x0080
CO_ITERABLE_COROUTINE = 0x0100

In [2]:
CO_FUTURE_DIVISION         = 0x2000
CO_FUTURE_ABSOLUTE_IMPORT  = 0x4000
CO_FUTURE_WITH_STATEMENT   = 0x8000
CO_FUTURE_PRINT_FUNCTION   = 0x10000
CO_FUTURE_UNICODE_LITERALS = 0x20000
CO_FUTURE_BARRY_AS_BDFL    = 0x40000
CO_FUTURE_GENERATOR_STOP   = 0x80000

In [ ]:
# code(argcount, kwonlyargcount, nlocals, stacksize, flags, 
#      codestring, constants, names, varnames, filename, name, 
#      firstlineno, lnotab[, freevars[, cellvars]])

my_code = CodeType(1,             # argcount 
                   0,             # kwonlyargcount
                   1,             # nlocals
                   2,             # stacksize
                   (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE),

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [1]:
def update(f, **kwds):
    "A function that performs a functional update on a function."
    old = f.__code__
    attrs = [
        'co_argcount', 'co_kwonlyargcount', 'co_nlocals', 
        'co_stacksize', 'co_flags', 'co_code', 'co_consts', 
        'co_names', 'co_varnames', 'co_filename', 'co_name', 
        'co_firstlineno', 'co_lnotab', 'co_freevars', 'co_cellvars',
    ]
    new = CodeType(*(kwds.get(a, getattr(old, a)) for a in attrs))
    
    return FunctionType(
        new, 
        f.__globals__, f.__name__, f.__defaults__, f.__closure__,
    )

In [ ]:


In [ ]:


In [4]:
from string import ascii_lowercase

def get_x(a, b, c, d, e, f, g, h, i, j, k, l, m, 
          n, o, p, q, r, s, t, u, v, w, x, y, z):
    "A function with **26** local variables."
    return x

In [ ]:


In [ ]:

Who are we?

  • We work at Quantopian.
  • GitHub:
    • github.com/ssanderson
    • github.com/llllllllll (10 lower-case L's)
  • Twitter:
    • @ssanderson
    • @\_\_qualname\_\_