◐ Shell
clean mode source ↗

GH-127058: Make `PySequence_Tuple` safer and probably faster. by markshannon · Pull Request #127758 · python/cpython

note that this pull request modifies the behavior of the following code

import time
class A:
	def __len__(self):
		raise NotImplementedError("infinite sequence")
	def __iter__(self):
		while True:
			time.sleep(1)
			yield 0

tuple(A())

before this change, the above raises an error. Now it enters an infinite loop.

by itself it isn't a problem because the fact that tuple() calls __len__ is an internal implementation detail and can be changed any time, but there isn't any other way for a class to declare itself as not convertible to list/tuple because it is infinite. There is no magic method __list__/__tuple__/__sequence__.

the same thing can be said about tuple(range(10**17))—before the change, immediate MemoryError; after it, consumes an increasing amount of memory before the process gets killed (don't try to run this).