Skip to content

Instantly share code, notes, and snippets.

@cdleary
Created August 11, 2011 05:01
Show Gist options
  • Save cdleary/1138936 to your computer and use it in GitHub Desktop.
Save cdleary/1138936 to your computer and use it in GitHub Desktop.
Rebinding in Python3
import types
from collections import namedtuple
class Oven:
def __init__(self):
self.pie = 'apple'
def easy_bake(self):
return self.pie
oven = Oven()
bound_method = oven.easy_bake
ovenish = namedtuple('OvenLikeThing', ['pie'])('cherry')
# Note: if you try to make a MethodType using bound_method, you get a type
# error on invocation, because of having too many things bound.
new_bound_method = types.MethodType(bound_method.__func__, ovenish)
assert new_bound_method() == 'cherry'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment