Skip to content

Instantly share code, notes, and snippets.

@Highstaker
Created October 13, 2016 15:44
Show Gist options
  • Select an option

  • Save Highstaker/901b812f06d72c858ed0fe5fae4e6e33 to your computer and use it in GitHub Desktop.

Select an option

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.
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