Skip to content

Instantly share code, notes, and snippets.

@lukmdo
Last active February 2, 2018 22:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lukmdo/e4972257b0f361884e28 to your computer and use it in GitHub Desktop.
Save lukmdo/e4972257b0f361884e28 to your computer and use it in GitHub Desktop.
meta without __metaclass__ (by inheritance)
from __future__ import print_function
from functools import wraps
class Fish(object):
def __new__(cls, *args, **kwargs):
o = super(Fish, cls).__new__(cls, *args, **kwargs)
o.foo_cache = {}
o.type = 'goldfish'
for name, val in vars(cls).items():
if name.startswith('foo_') and callable(val):
setattr(o, name, Fish.cache_foo_deco(val, o))
return o
def extra(self):
print("*" * 15)
def clear_foo_cache(self):
self.extra()
print("Clearing cache")
self.extra()
self.foo_cache.clear()
@staticmethod
def cache_foo_deco(func, o):
@wraps(func)
def wrapper(*args, **kwargs):
if func.__name__ not in o.foo_cache:
o.foo_cache[func.__name__] = func(o, *args, **kwargs)
return o.foo_cache[func.__name__]
return wrapper
class Cat(Fish):
def __init__(self):
if not hasattr(self, 'type'):
self.type = 'pussycat'
def iam(self):
print('I am a', self.type)
def foo_name(self):
print("processing lola")
return "lola"
def foo_type(self):
print("processing ani")
return "ani"
def main():
"""
>> main()
***************
I am a goldfish
***************
processing lola
lola
lola
lola
***************
processing ani
ani
ani
ani
***************
Clearing cache
***************
processing lola
lola
lola
lola
***************
processing ani
ani
ani
ani
"""
cat = Cat()
cat.extra()
Cat().iam()
cat.extra()
print(cat.foo_name())
print(cat.foo_name())
print(cat.foo_name())
cat.extra()
print(cat.foo_type())
print(cat.foo_type())
print(cat.foo_type())
cat.clear_foo_cache()
print(cat.foo_name())
print(cat.foo_name())
print(cat.foo_name())
cat.extra()
print(cat.foo_type())
print(cat.foo_type())
print(cat.foo_type())
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment