Other empty objects in Python evaluate as False — how can I get iterators/generators to do so as well?
Other empty objects in Python evaluate as False — how can I get iterators/generators
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
By default all objects in Python evaluate as
True. In order to supportFalseevaluations the object’s class must have either a__len__method (0->False), or a__nonzero__method (False->False). Note:__nonzero__==>__bool__in Python 3.x.Because the iterator protocol is intentionally kept simple, and because there are many types of iterators/generators that aren’t able to know if there are more values to produce before attempting to produce them,
True/Falseevaluation is not part of the iterator protocol.If you really want this behavior, you have to provide it yourself. One way is to wrap the generator/iterator in a class that provides the missing functionality.
Note that this code only evaluates to
FalseafterStopIterationhas been raised.As a bonus, this code works for pythons 2.4+
If you also want look-ahead (or peek) behavior, this code will do the trick (it evaluates to
FalsebeforeStopIterationis raised):Keep in mind that peek behaviour is not appropriate when the timing of the underlying iterator/generator is relevant to its produced values.
Also keep in mind that third-party code, and possibly the stdlib, may rely on iterators/generators always evaluating to
True. If you want peek without bool, remove the__nonzero__and__bool__methods.