Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Marmoset patching
import inspect
def marmoset_patch(func, s, r):
source = inspect.getsource(func).replace(s, r)
exec source in func.func_globals
func.func_code = func.func_globals[func.__name__].func_code
def foo():
print 1
print 2
print 3
foo()
# 1
# 2
# 3
marmoset_patch(foo, '3', "'ZOMG'")
foo()
# 1
# 2
# ZOMG
@davisagli

This comment has been minimized.

Copy link
Owner Author

davisagli commented Apr 6, 2012

Please, don't actually do this.

@gldnspud

This comment has been minimized.

Copy link

gldnspud commented Apr 6, 2012

Too late... you let the marmoset out of the bag!

@khs

This comment has been minimized.

Copy link

khs commented Apr 7, 2012

This seems like a good idea. Thank you for helping a new programmer out with learning new techniques. :) More seriously, what is monkey patching?

@codlark

This comment has been minimized.

Copy link

codlark commented Apr 7, 2012

@kellerkeller
a monkey patch is when you re-open an object for modification, some languages like ruby allow for this, and it's very common for large ruby apps to build classes out of several files. Python discourages monkey patching as looking through multiple files for where a method is defined gets tired fast, like the first time it happens, and as the Zen of Python tells us, explicit is better than implicit

@ctheune

This comment has been minimized.

Copy link

ctheune commented Mar 19, 2013

O M G

@sureshvv

This comment has been minimized.

Copy link

sureshvv commented Jun 23, 2013

Have the python people heard of this?

@miohtama

This comment has been minimized.

Copy link

miohtama commented Feb 17, 2014

This technique intrigues me. I look forward to apply it in many real-life scenarios.

@ztane

This comment has been minimized.

Copy link

ztane commented Feb 17, 2014

This is so wrong, the right solution is to use AST rewriting!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.