Last active
October 21, 2022 15:00
-
-
Save ivangeorgiev/764574575911bad9b413400d738513b5 to your computer and use it in GitHub Desktop.
Dynamic Method Binding in Python
This file contains hidden or 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
pytest |
This file contains hidden or 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 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(), {})] |
This file contains hidden or 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
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