Skip to content

Commit

Permalink
Add decorators to utility functions
Browse files Browse the repository at this point in the history
  • Loading branch information
cwacek committed Sep 12, 2013
1 parent edb30df commit 85109cf
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions inettopology/util/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import functools
import collections


class factory(object):
""" Decorate a function so that it becomes a cached factory."""

def __init__(self, func):
self.func = func
self.cache = {}

def __call__(self, *args):
if not isinstance(args, collections.Hashable):
return self.func(args)
if args in self.cache:
return self.cache[args]
else:
value = self.func(*args)
self.cache[args] = value
return value

def __doc__(self):
return self.func.__doc__

def __get__(self, obj, objtype):
'''Support instance methods'''
return functools.partial(self.__call__, obj)

0 comments on commit 85109cf

Please sign in to comment.