Created
October 13, 2016 15:44
-
-
Save Highstaker/901b812f06d72c858ed0fe5fae4e6e33 to your computer and use it in GitHub Desktop.
Pretty much a regular list, but when iterated over, it does not stop in the end. Instead, it iterates indefinitely.
This file contains hidden or 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 InfiniteListEmptyError(Exception): | |
| pass | |
| class InfiniteList(list): | |
| """ | |
| Pretty much a regular list, but when iterated over, it does not stop in the end. | |
| Instead, it iterates indefinitely. | |
| """ | |
| def __init__(self, arg): | |
| super(InfiniteList, self).__init__(arg) | |
| def __getattr__(self, name): | |
| if name == "it": | |
| # get iterator | |
| result = object.__getattribute__(self, name) | |
| else: | |
| try: | |
| result = super(InfiniteList, self).__getattribute__(name) | |
| except AttributeError: | |
| try: | |
| result = self.it.__getattribute__(name) | |
| except AttributeError: | |
| # Initialize iterator cuz it's not initialized | |
| self.__iter__() | |
| result = self.it.__getattribute__(name) | |
| return result | |
| def __iter__(self): | |
| it = super(InfiniteList, self).__iter__() | |
| self.it = it | |
| return self | |
| def __next__(self): | |
| try: | |
| result = next(self.it) | |
| except StopIteration: | |
| self.__iter__() | |
| try: | |
| result = next(self.it) | |
| except StopIteration: | |
| raise InfiniteListEmptyError("Could not iterate. List is empty!") | |
| return result | |
| # TESTS | |
| a = InfiniteList(tuple()) #empty list | |
| print(a) | |
| print(a.__length_hint__()) #testing iterator attributes | |
| print(a.__eq__([1,3,5])) # false | |
| # should raise exception, since the list is empty | |
| try: | |
| for i in a: | |
| print(i) | |
| except InfiniteListEmptyError: | |
| print("List is empty!") | |
| a.append(1) | |
| a.extend([3,5]) | |
| print(a) | |
| print(a[1]) | |
| print(a.__eq__([1,3,5])) #true | |
| # infinite loop | |
| for i in a: | |
| print(i) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment