Reputation: 8639
I encounter a weird error. As these codes, both foo()
and bar()
return None
, but it raises TypeError only when iterating bar()
def foo():
if True:
return
yield 1, 2
def bar():
return
for a, b in foo():
print a + b
for a, b in bar():
print a + b
Upvotes: 2
Views: 2360
Reputation: 390
If your function does not include yield statement and you want it to return "empty iterator" you should write
def empty()
raise StopIteration
for each in empty():
print('this will never show up')
Upvotes: 2
Reputation: 702
The yield 1, 2 makes the difference. foo returns:
<generator object foo at 0x7f9e01a91d70>
bar returns:
None
If you'd comment the yield part the code would crash on foo() too.
You should return two values for each of the methods to solve it.
Upvotes: 1
Reputation: 5231
In your functions foo
and bar
, they both reach an empty return
statement. They implicitly return None
. foo
will nonetheless generate an iterator as it includes a yield
statement.
Therefore as you are looping over the output of the functions, foo
will use the iterator values, while bar
will not, resulting in a TypeError
.
Upvotes: 0
Reputation:
If you
print foo()
print bar()
you get
<generator object foo at 0x7f8a79fd5eb0>
None
Upvotes: 1
Reputation: 600041
Because foo
includes a yield
statement, it is a generator, so the result from the return is always a generator object even if the actual yield statement can't be reached. A generator is true in a boolean sense, hence your result.
Upvotes: 5