Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- In [79]: _cache = {}
- In [80]: def cached(cls):
- ...: from functools import wraps
- ...: import inspect
- ...: sig = inspect.signature(cls)
- ...: @wraps(cls)
- ...: def wrapped(*args, **kwargs):
- ...: bound_values = sig.bind(*args, **kwargs)
- ...: bound_values.apply_defaults()
- ...: s = frozenset(bound_values.arguments.items())
- ...: if s in _cache:
- ...: return _cache[s]
- ...: _cache[s] = cls(*args, **kwargs)
- ...: return _cache[s]
- ...: return wrapped
- ...:
- In [81]: @cached
- ...: class Spam:
- ...: def __init__(self, x, y, z=None):
- ...: self.x = x
- ...: self.y = y
- ...: self.z = z
- ...:
- In [82]: s1 = Spam(10, 20)
- In [83]: s2 = Spam(x=10, y=20)
- In [84]: s1 is s2
- Out[84]: True
- In [85]: s3 = Spam(x=10, y=20, z=None)
- In [86]: s2 is s3
- Out[86]: True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement