Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
class Cached(object):
"""Cache classes with positional arguments."""
_cache = {}
def __new__(cls, *args):
if args not in cls._cache:
cls._cache[args] = super(Cached, cls).__new__(cls)
return cls._cache[args]
class RangeSet(Cached):
"""RangeSet([start,] stop [, step]) -> cross between range and set"""
def __init__(self, *args):
self._list = range(*args)
self._set = frozenset(self._list)
if len(args) == 1:
self._start, self._stop, self._step = 0, args[0], 1
elif len(args) == 2:
self._start, self._stop = args
self._step = 1
self._start, self._stop, self._step = args
def start(self):
return self._start
def stop(self):
return self._stop
def step(self):
return self._step
def __contains__(self, value):
return value in self._set
def __eq__(self, other):
return self._set == other._set
except AttributeError:
return self._set == other
def __getitem__(self, index):
return self._list[index]
def __hash__(self):
return hash(self._set)
def __iter__(self):
return iter(self._list)
def __repr__(self):
return 'RangeSet({0.start}, {0.stop}, {0.step})'.format(self)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment