-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |