Interesting little "gotcha" with generators
Will McGugan
news at NOwillmcguganSPAM.com
Thu Dec 22 17:22:25 EST 2005
Kenneth McDonald wrote:
> I recently had need to write the following code:
>
> def compileOuter(self):
> if False: yield None
> else: return
>
> "compileOuter" is a generator function which is implemented in various
> classes. In this particular class, it always yields nothing. However,
> none of the following work:
>
> def compileOuter(self):
> return
>
> def compileOuter(self):
> pass
>
> def compileOuter(self):
> yield
>
> The first two don't work because in order to define a generator, you
> must have a yield statement inside it. The last doesn't work because
> every "yield" must have an argument.
>
> I've been using "return" in generators ever since I started using
> generators, but on reflection, it seems to me that such a thing is in
> some ways inconsistent; "return" is (conceptually, at least originally)
> a function statement, where "return" by itself really stands in for
> "return None". But in generators, it is being used as a control flow
> command. For example, you can't have "return" with an argument inside a
> generator.
>
> Too bad "return" wasn't entirely forbidden within generators, and
> "yield" without an argument mandated instead. Oh well, too let now I
> suppose...
Would this work?
def compilerOuter(self):
raise StopIteration
Will McGugan
--
http://www.willmcgugan.com
"".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in
"jvyy*jvyyzpthtna^pbz")
More information about the Python-list
mailing list