Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

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.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6752501
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T13:03:08+00:00 2026-05-26T13:03:08+00:00

Other empty objects in Python evaluate as False — how can I get iterators/generators

  • 0

Other empty objects in Python evaluate as False — how can I get iterators/generators to do so as well?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T13:03:08+00:00Added an answer on May 26, 2026 at 1:03 pm

    By default all objects in Python evaluate as True. In order to support False evaluations 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/False evaluation 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 False after StopIteration has been raised.

    As a bonus, this code works for pythons 2.4+

    try:
        next
    except NameError:       # doesn't show up until python 2.6
        def next(iter):
            return iter.next()
    
    Empty = object()
    
    class Boolean_Iterator(object):
        """Adds the abilities
        True/False tests:  True means there /may/ be items still remaining to be used
        """
        def __init__(self, iterator):
            self._iter = iter(iterator)
            self._alive = True
        def __iter__(self):
            return self
        def __next__(self):
            try:
                result = next(self._iter)
            except StopIteration:
                self._alive = False
                raise
            return result
        next = __next__                     # python 2.x
        def __bool__(self):
            return self._alive
        __nonzero__ = __bool__              # python 2.x
    

    If you also want look-ahead (or peek) behavior, this code will do the trick (it evaluates to False before StopIteration is raised):

    try:
        next
    except NameError:       # doesn't show up until python 2.6
        def next(iter):
            return iter.next()
    
    Empty = object()
    
    class Iterator(object):
        """Adds the abilities
        True/False tests:  True means there are items still remaining to be used
        peek(): get the next item without removing it from the sequence
        """
        def __init__(self, iterator):
            self._iter = iter(iterator)
            self._peek = Empty
            self.peek()
        def __next__(self):
            peek, self._peek = self._peek, Empty
            self.peek()
            if peek is not Empty:
                return peek
            raise StopIteration
        next = __next__                     # python 2.x
        def __bool__(self):
            return self._peek is not Empty
        __nonzero__ = __bool__              # python 2.x
        def peek(self):
            if self._peek is not Empty:
                return self._peek
            self._peek = next(self._iter, Empty)
            return self._peek
    

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can an XML attribute be the empty string? In other words, is <element att=
Null or empty string -- is one better than the other to represent no
What results when you pass an empty String (or some other unrecognized value, or
I can't create an utf-8 csv file in Python. I'm trying to read it's
The site I'm working on involves teachers creating student objects. The teacher can choose
I have a Python set that contains objects with __hash__ and __eq__ methods in
I'm adding an array of Panel objects (which in turn contain other items) to
Often I add an Empty method to my C++ objects to clear the internal
I have a unit test which contains the following line of code Site.objects.get(name=UnitTest).delete() and
I have two objects, and one inherites from the other. the parent object sends

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.