Skip to content

Instantly share code, notes, and snippets.

@gabrielfalcao
Created October 7, 2009 20:00
Show Gist options
  • Save gabrielfalcao/204392 to your computer and use it in GitHub Desktop.
Save gabrielfalcao/204392 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
# Copyright (C) <2009> Gabriel Falcão <gabriel@nacaolivre.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from datetime import datetime
def cached(func):
func.should_be_cached = True
return func
class Cacheable(object):
__CACHE__ = {}
def cache_that(self, func):
def wrapper(*args, **kw):
name = "%s%r%r" % (func.__name__, args, kw)
if name not in self.__CACHE__:
self.__CACHE__[name] = func(*args, **kw)
return self.__CACHE__[name]
wrapper.__name__ = func.__name__
return wrapper
def __getattribute__(self, attr):
function = super(Cacheable, self).__getattribute__(attr)
if attr != 'cache_that' and callable(function) and hasattr(function, 'should_be_cached'):
return self.cache_that(function)
return function
class Modafoca(Cacheable):
@cached
def alguma_coisa(self):
return datetime.now()
@cached
def com_param(self, age, outro=None):
return "%s%r%r" % (datetime.now(), age, outro)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment