def get_data(batchsize=None):
conn = psycopg2.connect('database parameter')
cursor = conn.cursor()
query = 'select * from table'
cursor.execute(query)
if not batchsize:
result = cursor.fetchall()
return result
else:
while True:
result = cursor.fetchmany(batchsize)
if not result:
break
yield result
if __name__ == '__main__':
data = get_data()
In above function type of data should have been a list as argument batchsize=None. but this function is returning generator in both cases. If I comment else part of the function then it's returning a list.
Ah, I got what you're asking about. You're asking:
Why do I still receive a generator even if I don't hit
yieldkeyword inget_data()?
The thing is that a function, which contains at least one yield statement is a generator. So your get_data() function is a generator. Because of that you always receive a generator object out of get_data().
The meaning of return in a generator is a bit different from ordinary function. In a generator any return x statement is equivalent to raise StopIteration(x).
And when you comment out part with else, you comment out yield statement, so get_data() becomes an ordinary function. Therefore it returns a list as you expect.
Related SO post: Return and yield in the same function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With