Skip to content

Instantly share code, notes, and snippets.

@a-recknagel
Created August 15, 2019 14:59
Show Gist options
  • Save a-recknagel/768ca2ee2528e2367b8d6ee71fbcdfa3 to your computer and use it in GitHub Desktop.
Save a-recknagel/768ca2ee2528e2367b8d6ee71fbcdfa3 to your computer and use it in GitHub Desktop.
simple proxy
from collections import defaultdict
class Proxy:
def __init__(self, instance):
self.instance = instance
self.last_call = None
self.call_map = defaultdict(int)
def __getattr__(self, name):
self.last_call = name
self.call_map[name] += 1
return getattr(self, instance, name)
def last_invoked_method(self):
return self.last_call
def count_of_calls(self, name):
return self.call_map[name]
def was_called(self, name):
return self.call_map[name] > 0
class Foo:
def bar(self, text):
return f'bar: {text}'
def baz(self, text):
return f'baz: {text}'
def qux(self, text):
return f'qux: {text}'
proxy = Proxy(Foo())
proxy.foo('xyz')
# foo: xyz
proxy.bla
# Traceback (most recent call last):
# ...
# AttributeError: 'Foo' object has no attribute 'bla'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment