PEP 255: Simple Generators, Revised Posting
Tim Peters
tim.one at home.com
Sun Jun 24 22:23:45 EDT 2001
[Bernhard Herzog]
> I wasn't aware of that! For that matter, I wasn't even aware that the
> compiler removed "if 0" blocks. When was that introduced. It even
> "works" with 1.5.2.
It was introduced along with "assert": under the covers, assert gets
changed into
if __debug__:
do the assert code
__debug__ is a compile-time constant, and it was thought important that
asserts leave no trace (not even bytecode) under -O. The mechanism for
getting rid of
if __debug__:
at compile-time just happens to recognize literal numeric zeroes and empty
strings as meaning "false" too.
> ...
> you need to introduce a yield statement and make sure that it's never
> executed. The following works:
>
> >>> def g():
> .. if ():
> .. yield 0
> ..
> >>> for i in g():
> .. print i
> ..
> >>>
>
> The compiler apparently isn't smart enough to think of () as a constant
> (the bytecode confirms that).
Right, it only knows about numbers, strings and the specific name
"__debug__".
> Being able to easily write a function that does nothing (in fact it's
> the most trivial function one can write) is very useful in practice, so
> as a generalization being able to write empty generators might be
> useful, too. I'm not sure about that, though, because I don't have
> enough experience with them.
Can't say I see much use for it. If I did, I'd probably write what
everybody hates:
def emptyg():
return
yield None # never reached
Stick that in a utility module and you'll never have to think about it
again.
haven't-needed-an-always-empty-generator-yet-ly y'rs - tim
More information about the Python-list
mailing list