Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantages of Python generators?

Everyone talks about advantages using generators in Python. It's really cool and useful thing. But no one speaks about their disadvantages. And interviewers usually use this gap.

So is there any other disadvantage of using generators besides these two?

  1. For the generator's work, you need to keep in memory the variables of the generator function.
  2. Every time you want to reuse the elements in a collection it must be regenerated.
like image 636
Raymond Reddington Avatar asked Oct 17 '25 13:10

Raymond Reddington


1 Answers

  1. For the generator's work, you need to keep in memory the variables of the generator function.

But you don't have to keep the entire collection in memory, so usually this is EXACTLY the trade-off you want to make.

  1. Every time you want to reuse the elements in a collection it must be regenerated.

The generator must be recreated, but the collection does not need to be though. So this may not be a problem.

Essentially it boils down to a discussion about Lazy vs Eager evaluation. You trade-off CPU overhead for the capability of streaming processing (as opposed to bulk-processing with eager evaluation). The code can become a bit more tricky to read if using a lazy approach, so there could be a trade-off between performance and simplicity there as well.

like image 174
Morten Jensen Avatar answered Oct 20 '25 03:10

Morten Jensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!