[Python 3.8 | Spyder]
I was trying to introduce a simple definition that would either return [1,2,3]
or yield
the numbers sequentially.
The minimum working code is as follows:
def example(condition):
if condition:
yield 1
yield 2
yield 3
else:
return [1,2,3]
If one attempts to use the def
, it will always return a generator. Even if the return
appears first in the if/else pair:
def example(condition):
if not condition:
return [1,2,3]
else:
yield 1
yield 2
yield 3
It seems python is not ignoring the presence of the yields even if condition = False
.
This is an unexpected behaviour.
You can return the generator in the form of a generator expression:
>>> def example(condition):
... if condition:
... return (i for i in (1, 2, 3))
... else:
... return [1, 2, 3]
>>> example(1)
<generator object example.<locals>.<genexpr> at 0x000000000257BBA0>
>>> example(0)
[1, 2, 3]
Or you can define the generator separately:
>>> def g():
... yield 1
... yield 2
... yield 3
...
>>> def example(condition):
... if condition:
... return g()
... else:
... return [1, 2, 3]
>>> example(1)
<generator object g at 0x000000000257BBA0>
>>> example(0)
[1, 2, 3]