Skip to content

Instantly share code, notes, and snippets.

@ivangeorgiev
Last active October 21, 2022 15:00
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 ivangeorgiev/764574575911bad9b413400d738513b5 to your computer and use it in GitHub Desktop.
Save ivangeorgiev/764574575911bad9b413400d738513b5 to your computer and use it in GitHub Desktop.
Dynamic Method Binding in Python

Dynamic Method Binding in Python

import types as t
class User:
def save(self):
raise NotImplementedError()
class TestBinding:
def test_bind_with_types_methodtype(self):
def save(self, *args, **kwargs):
calls.append((self, args, kwargs))
calls = []
u = User()
# Replace the original method
u.save = t.MethodType(save, u)
# Call the replaced method
u.save()
# Assert the actual implementation was called
assert calls == [(u, tuple(), {})]
class User:
def save(self):
raise NotImplementedError()
class TestBinding:
def test_bind_with_setattr(self):
def save(self, *args, **kwargs):
calls.append((self, args, kwargs))
calls = []
u = User()
# Replace the method
u.save = save.__get__(u, u.__class__)
# Call the replaced method
u.save()
# Assert replacement is called
assert calls == [(u, tuple(), {})]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment