"return" in def

John Machin sjmachin at lexicon.net
Sun Dec 28 17:02:03 EST 2008


On Dec 29, 8:36 am, Benjamin <musiccomposit... at gmail.com> 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.

What gave you that impression?

<experimentation>

Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
...    for i in range(4):
...       yield i
...    return
...
>>> foo
<function foo at 0x00F5AF30>
>>> x = foo()
>>> x
<generator object foo at 0x00F61080>
>>> list(x)
[0, 1, 2, 3]
>>> def bar():
...    for i in range(4):
...       yield i
...    return 42
...
  File "<stdin>", line 4
SyntaxError: 'return' with argument inside generator

</experimentation>

<manual>

(go to http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy
then scroll down)

Generator functions

    A function or method which uses the yield statement (see section
The yield statement) is called a generator function. Such a function,
when called, always returns an iterator object which can be used to
execute the body of the function: calling the iterator’s next() method
will cause the function to execute until it provides a value using the
yield statement. When the function executes a return statement or
falls off the end, a StopIteration exception is raised and the
iterator will have reached the end of the set of values to be
returned.

</manual>



More information about the Python-list mailing list