Just for fun, there is something that does just what you want. By default, it associates a loop variable with the name "_each", but you can override this with your own choice by providing it with an argument var.
import inspect
class foreach(object):
__OBJ_NAME = '_foreach'
__DEF_VAR = '_each'
def __init__(self, iterable, var=__DEF_VAR):
self.var = var
f_locals = inspect.currentframe().f_back.f_locals
if self.var not in f_locals:
self.iterable = iter(iterable)
f_locals[self.__OBJ_NAME] = self
f_locals[self.var] = self.iterable
else:
obj = f_locals[self.__OBJ_NAME]
self.iterable = obj.each = obj.iterable
def __nonzero__(self):
f_locals = inspect.currentframe().f_back.f_locals
try:
f_locals[self.var] = self.iterable.next()
return True
except StopIteration:
del f_locals[self.var]
del f_locals[self.__OBJ_NAME]
return False
some_array = [10,2,4]
while foreach(some_array):
print _each
print
while foreach("You can do (almost) anything in Python".split(), var='word'):
print word
source
share