Skip to content

Instantly share code, notes, and snippets.

@tzickel
Created January 29, 2018 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzickel/18f1d6aedf71c82b5f81095c590c529b to your computer and use it in GitHub Desktop.
Save tzickel/18f1d6aedf71c82b5f81095c590c529b to your computer and use it in GitHub Desktop.
A simple example on how to patch a constant in a python 2 function
import new
class Empty(object):
pass
def patch_const(func, const_index, new_value, previous_value=Empty):
co = func.func_code
consts = list(co.co_consts)
if previous_value is not Empty:
if consts[const_index] != previous_value:
raise RuntimeError('Wrong value for const: %s' % (consts[const_index]))
consts[const_index] = new_value
consts = tuple(consts)
new_code = new.code(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab)
func.func_code = new_code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment