Are generators in nested functions possible?
Chris Liechti
cliechti at gmx.net
Thu Jun 20 19:51:14 EDT 2002
"Bjorn Pettersen" <BPettersen at NAREX.com> wrote in
news:mailman.1024614876.11270.python-list at python.org:
> I've got the following code to generate the indicies of all nearest
> neighbours (span levels) in a multi dimensional qube:
>
> def generateIndexes(length=5, span=1):
> spanvalues = range(-span, span+1)
>
> def genInd(res, length):
> if length == 1:
> for val in spanvalues:
> yield res + [val]
> else:
> for i in range(length):
> for val in spanvalues:
> genInd(res + [val], length-1)
here you generate generator objetcs and throw them away 'cause you dont use
them in a loop aor anything!
if you replace that last line with:
for x in genInd(res + [val], length-1):
yield x
it yields some data, don't know if it's what you want ;-)
chris
> return genInd([], length)
>
> However, when I try to use it it doesn't seem to return anything:
>
> >>> for i in generateIndexes(3):
> ... print i
> ...
> >>>
>
> I tried getting the iterator (or is it generator?) directly and calling
> next() on it, and it seems like it raises a StopIteration exception
> immediately:
>
> >>> g = generateIndexes(3)
> >>> g.next()
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> StopIteration
> >>>
>
> Can anyone help me understand what is going on here?
>
> -- bjorn
>
>
>
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list