#18963: Pattern for object model compatibility isn't friendly for subclasses
------------------------------------------------+------------------------
               Reporter:  aaugustin             |          Owner:  nobody
                   Type:  Cleanup/optimization  |         Status:  new
              Component:  Python 3              |        Version:  master
               Severity:  Normal                |       Keywords:
           Triage Stage:  Unreviewed            |      Has patch:  0
    Needs documentation:  0                     |    Needs tests:  0
Patch needs improvement:  0                     |  Easy pickings:  0
                  UI/UX:  0                     |
------------------------------------------------+------------------------
 In the [https://docs.djangoproject.com/en/dev/topics/python3/#magic-
 methods Python 3 documentation] I recommended the following pattern for
 iterators:

 {{{
 class MyIterator(object):
     def __iter__(self):
         return self             # implement some logic here

     def __next__(self):
         raise StopIteration     # implement some logic here

     next = __next__             # Python 2 compatibility
 }}}

 A downside is that if a subclass overrides `__next__`, it also has to
 repeat `next = __next__`. This is tricky.

 As of [20012b96] Django bundles six 1.2, which introduced
 [http://packages.python.org/six/#six.Iterator six.Iterator] to solve this
 problem.

 This problem cannot cause regressions for people who have working code on
 Python 2, because they override `next`, not `__next__`. However I'd like
 to take advantage of `six.Iterator` since it's technically more correct.

 ----

 The same problem exists with `__nonzero__ = __bool__`, `__div__ =
 __truediv__` and `__idiv__ = __truediv__`.

 We could use a slightly more verbose pattern:
 {{{
 class Foo(object):
     def __nonzero__(self):
         return self.__bool__()
 }}}

 `six.Iterator` uses `type(self).__next__(self)` rather than
 `self.__next__()`. I assume there's a good reason but I haven't figured it
 out. I'd like to understand it before making a decision.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/18963>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To post to this group, send email to django-updates@googlegroups.com.
To unsubscribe from this group, send email to 
django-updates+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to