(Disclaimer: never use this code for any remotely serious purpose)
The problem with changing the value of i in your code is this: usually assignments (including added assignment, += ) made for local immutable values ββare visible only in the local area. The inside of range not in the local area. When you reassign i , the range implementation does not know this.
Usually.
But Python has a built-in module called inspect that provides all the information about your program that you normally would not want to be included at runtime. This includes the values ββof variables in frames that would otherwise be completely inaccessible.
In violation of good programming principles and laws of nature, we can write a range-like function that breaks the veil of ignorance and steals the value of i from a challenging context, just as Prometheus stole fire from Mount Olympus peak. (Note: remember what happens to Prometheus at the end of this story.)
import inspect import re def mutable_range(max): x = 0 while x < max: yield x record = inspect.stack()[1] frame = record[0] source_lines = record[4] iterator_name = re.match(r"\s*for (\w+) in mutable_range", source_lines[0]).group(1) peek = frame.f_locals[iterator_name] if peek != x: x = peek else: x += 1 for i in mutable_range(10): print(i) if i == 3: i = -10 if i == -8: i = 6
Result:
0 1 2 3 -10 -9 -8 6 7 8 9
(Disclaimer: The author is not responsible for the use of the code and the subsequent punishment of your arrogance by the eagles that feed your liver for all eternity)
Kevin
source share