Skip to content

Instantly share code, notes, and snippets.

@lmazuel
Created June 3, 2019 21:21
Show Gist options
  • Save lmazuel/1840fdf15099c757c6a863fe9b60a76e to your computer and use it in GitHub Desktop.
Save lmazuel/1840fdf15099c757c6a863fe9b60a76e to your computer and use it in GitHub Desktop.
Metaclass
from functools import wraps
from six import add_metaclass
class MetaCount(type):
def __new__(cls, *args, **kwargs):
obj = super(MetaCount, cls).__new__(cls, *args, **kwargs)
obj.read_count = 0
if hasattr(obj, 'read'):
original_read = obj.read
@wraps(original_read)
def read_count(*args, **kwargs):
obj.read_count += 1
return original_read(*args, **kwargs)
obj.read = read_count
return obj
@add_metaclass(MetaCount)
class Toto(object):
def read(self):
"""MyDoc."""
return "Foo"
t = Toto()
t.read()
t.read()
assert "MyDoc" in t.read.__doc__
assert t.read_count == 2
assert t.read() == "Foo"
assert t.read_count == 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment