Opened 7 years ago

Closed 6 years ago

#18802 closed enhancement (fixed)

Python 3 preparation: Iterator protocol uses .next() in Py2 but __next__() in Py3

Reported by: Wilfried Luebbe Owned by:
Priority: major Milestone: sage-7.4
Component: python3 Keywords:
Cc: Merged in:
Authors: André Apitzsch Reviewers: Frédéric Chapoton
Report Upstream: N/A Work issues:
Branch: 840f968 (Commits, GitHub, GitLab) Commit: 840f9686d78fe1a739bec9f9badaf985bba5c341
Dependencies: Stopgaps:

Status badges

Description (last modified by Wilfried Luebbe)

When defining a custom iterator one has to define a method that returns the next item. In Python 3 this method is called next() while in Python 3 this is the special method __next__().

More information can be found in http://python-future.org/compatible_idioms.html#custom-iterators and http://python-future.org/what_else.html#custom-iterators.

Remark: To advance some iterator it in Py2 often this method is called directly it.next(). But since Python 2.6 there is the builtin function next() which is compatible between Py2 and Py3: in Py2 it calls the iterator method next() while in Py3 it calls the special method __next__(). Ticket #16075 addresses the (stage 1) conversion from it.next() to next(it).

This ticket is tracked as a dependency of meta-ticket #16052.

Change History (9)

comment:1 Changed 7 years ago by Wilfried Luebbe

Description: modified (diff)

comment:2 Changed 7 years ago by Wilfried Luebbe

Description: modified (diff)

comment:3 Changed 7 years ago by Jeroen Demeyer

Component: miscpython3

comment:4 Changed 6 years ago by aapitzsch

Authors: André Apitzsch
Branch: u/aapitzsch/18802
Commit: 840f9686d78fe1a739bec9f9badaf985bba5c341
Milestone: sage-6.8sage-7.4
Status: newneeds_review

New commits:

840f968rename next() to __next__() and keep next() as alias

comment:5 Changed 6 years ago by Frédéric Chapoton

Are you sure that all these things are really iterators ?

comment:6 in reply to:  5 Changed 6 years ago by aapitzsch

Replying to chapoton:

Are you sure that all these things are really iterators ?

Yes.

comment:7 Changed 6 years ago by Frédéric Chapoton

I do not quite agree with that. The next methods in permutation and partition are not really iterators (they are implemented on elements, not on a set, and they return False when they cannot return something), and should in fact not be called using next(p) but rather as a method p.next(). Of course, it may be convenient to use next(p) as a shortcut, but this is not the usual semantics of iterators, so I would rather deprecate that.

comment:8 Changed 6 years ago by Frédéric Chapoton

Reviewers: Frédéric Chapoton
Status: needs_reviewpositive_review

ok, let us do that, despite the fact that some are not really iterators.

comment:9 Changed 6 years ago by Volker Braun

Branch: u/aapitzsch/18802840f9686d78fe1a739bec9f9badaf985bba5c341
Resolution: fixed
Status: positive_reviewclosed
Note: See TracTickets for help on using tickets.