"return" in def

Robert Kern robert.kern at gmail.com
Sun Dec 28 22:57:51 CET 2008


Benjamin wrote:
> On Dec 28, 1:35 pm, Steven D'Aprano <st... at REMOVE-THIS-
> cybersource.com.au> wrote:
>> The second thing I think is that maybe the function is a generator, and
>> so I look for a yield.
> 
> You shouldn't, though; Generators can't contain any return statement.

Yes, they can. It doesn't return a value, it just raises a StopIteration error.

In [18]: def g():
     for i in range(5):
         if i == 3:
             print 'Early exit.'
             return
             print 'Should not happen.'
         yield i
    ....:
    ....:

In [25]: list(g())
Early exit.
Out[25]: [0, 1, 2]

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list