Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def modify_builtin_types(f, changes, recursive=True):
- # Extract code
- mod_code = f.__code__
- mod_consts = list(mod_code.co_consts)
- # Modify code
- for index, elem in enumerate(mod_consts):
- try:
- mod_consts[index] = changes[type(elem)](elem)
- except KeyError:
- pass
- # Create new code
- f.__code__ = type(mod_code)(
- mod_code.co_argcount, mod_code.co_nlocals,
- mod_code.co_stacksize, mod_code.co_flags, mod_code.co_code,
- tuple(mod_consts), mod_code.co_names, mod_code.co_varnames,
- mod_code.co_filename, mod_code.co_name, mod_code.co_firstlineno,
- mod_code.co_lnotab, mod_code.co_freevars, mod_code.co_cellvars,
- )
- class ImprovedInt(int):
- current = 0
- def __iter__(self):
- return self
- def next(self):
- if self.current >= self:
- raise StopIteration
- else:
- self.current += 1
- return self.current - 1
- def f():
- for i in 10:
- print i
- modify_builtin_types(f, {int: ImprovedInt})
- f()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement