[Python-Dev] Half-baked proposal: * (and **?) in assignments
John Williams
jrw@pobox.com
Mon, 25 Nov 2002 14:58:01 -0600
Alex Martelli wrote:
> What WOULD be intolerable, it appears to me, would be to *require*
> that user-coded iterators (classes exposing currently-suitable
> __iter__ and next methods) MUST subclass iter. That would break
> existing, running code, and go against the grain of Python, which
> nowhere else imposes such requirements. Having a (mix-in?) class that
> iterators COULD subclass (as Brent suggests) is one thing; for Python
> to REQUIRE such subtyping (as Armin appears to wish could be done) is
> quite another.
What if you turn this around and place the burden on the Python system?
Make "iter" a class rather than a function, and ensure that
iter.__new__ always returns a subclass of "iter" like this (untested code):
class iter(object):
def __new__(cls, iterable):
userIterator = iterable.__iter__()
if isinstance(userIterator, iter):
# Just like today's "iter" function.
return userIterator
else:
# Build a wrapper.
wrapper = object.__new__(iter)
wrapper.next = userIterator.next
if hasattr(userIterator, "__iter__"):
wrapper.__iter__ = userIterator.__iter__
return wrapper
def next(self):
raise NotImplementedError
def __iter__(self):
return self
# arbitrary new convenience methods here
--jw