Created
November 2, 2020 17:30
-
-
Save objarni/bb4743463d2a65f12c25283ac6c0a46b to your computer and use it in GitHub Desktop.
Simple class attribute spy for 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
class Spy: | |
# replace getattr of class and collect all calls | |
# and the return the underlying class' getattr | |
def __init__(self, cls): | |
self.spy_on = cls.__name__ | |
self.cls_getattr = cls.__getattribute__ | |
self.cls_getitem = cls.__getitem__ | |
self.attributes_read = set() | |
self.items_read = set() | |
def spy_getattribute(instance, attr): | |
self.attributes_read.add(attr) | |
return (self.cls_getattr)(instance, attr) | |
def spy_getitem(instance, item): | |
self.items_read.add(item) | |
return (self.cls_getitem)(instance, item) | |
cls.__getattribute__ = spy_getattribute | |
cls.__getitem__ = spy_getitem | |
def report(self): | |
return f""" | |
Spied on {self.spy_on}. | |
These attributes were read: | |
{', '.join(sorted(self.attributes_read))} | |
These items were read: | |
{', '.join(sorted(self.items_read))} | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment