Created
January 29, 2018 18:20
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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