Last active
August 29, 2015 14:14
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
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 | |
else: | |
self._start, self._stop, self._step = args | |
@property | |
def start(self): | |
return self._start | |
@property | |
def stop(self): | |
return self._stop | |
@property | |
def step(self): | |
return self._step | |
def __contains__(self, value): | |
return value in self._set | |
def __eq__(self, other): | |
try: | |
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