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

  • SEARCH
  • Home
  • 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 276537
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T00:56:09+00:00 2026-05-12T00:56:09+00:00

As part of some WSGI middleware I want to write a python class that

  • 0

As part of some WSGI middleware I want to write a python class that wraps an iterator to implement a close method on the iterator.

This works fine when I try it with an old-style class, but throws a TypeError when I try it with a new-style class. What do I need to do to get this working with a new-style class?

Example:

class IteratorWrapper1:

    def __init__(self, otheriter):
        self._iterator = otheriter
        self.next = otheriter.next

    def __iter__(self):
        return self

    def close(self):
        if getattr(self._iterator, 'close', None) is not None:
            self._iterator.close()
        # other arbitrary resource cleanup code here

class IteratorWrapper2(object):

    def __init__(self, otheriter):
        self._iterator = otheriter
        self.next = otheriter.next

    def __iter__(self):
        return self

    def close(self):
        if getattr(self._iterator, 'close', None) is not None:
            self._iterator.close()
        # other arbitrary resource cleanup code here

if __name__ == "__main__":
    for i in IteratorWrapper1(iter([1, 2, 3])):
        print i

    for j in IteratorWrapper2(iter([1, 2, 3])):
        print j

Gives the following output:

1
2
3
Traceback (most recent call last):
  ...
TypeError: iter() returned non-iterator of type 'IteratorWrapper2'
  • 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-12T00:56:09+00:00Added an answer on May 12, 2026 at 12:56 am

    What you’re trying to do makes sense, but there’s something evil going on inside Python here.

    class foo(object):
        c = 0
        def __init__(self):
            self.next = self.next2
    
        def __iter__(self):
            return self
    
        def next(self):
            if self.c == 5: raise StopIteration
            self.c += 1
            return 1
    
        def next2(self):
            if self.c == 5: raise StopIteration
            self.c += 1
            return 2
    
    it = iter(foo())
    # Outputs: <bound method foo.next2 of <__main__.foo object at 0xb7d5030c>>
    print it.next
    # 2
    print it.next()
    # 1?!
    for x in it:
        print x
    

    foo() is an iterator which modifies its next method on the fly–perfectly legal anywhere else in Python. The iterator we create, it, has the method we expect: it.next is next2. When we use the iterator directly, by calling next(), we get 2. Yet, when we use it in a for loop, we get the original next, which we’ve clearly overwritten.

    I’m not familiar with Python internals, but it seems like an object’s “next” method is being cached in tp_iternext (http://docs.python.org/c-api/typeobj.html#tp_iternext), and then it’s not updated when the class is changed.

    This is definitely a Python bug. Maybe this is described in the generator PEPs, but it’s not in the core Python documentation, and it’s completely inconsistent with normal Python behavior.

    You could work around this by keeping the original next function, and wrapping it explicitly:

    class IteratorWrapper2(object):
        def __init__(self, otheriter):
            self.wrapped_iter_next = otheriter.next
        def __iter__(self):
            return self
        def next(self):
            return self.wrapped_iter_next()
    
    for j in IteratorWrapper2(iter([1, 2, 3])):
        print j
    

    … but that’s obviously less efficient, and you should not have to do that.

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

Sidebar

Related Questions

As part of the base class for some extensive unit testing, I am writing
I have some tables that I build as a part of my report rollup.
I need to write some javascript to strip the hostname:port part from a url,
I have a two part question Best-Practice I have an algorithm that performs some
As part of some error handling in our product, we'd like to dump some
For part of a web application the user needs to import some data from
Part of the install for an app I am responsible for, compiles some C
I'm generating some XML documents and when it comes to the address part I
I was refactoring some code, and part of it included moving it from VB.Net
When databinding my xaml to some data I often use the get part of

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.