Skip to content

Commit

Permalink
Trac #21266: py3: get rid of iterkeys
Browse files Browse the repository at this point in the history
as a step towards py3, do not use iterkeys

(there remains 3 more subtle uses of iterkeys)

I have also taken the opprtunity to remove deprecated code in
src/sage/combinat/finite_state_machine.py

URL: https://trac.sagemath.org/21266
Reported by: chapoton
Ticket author(s): Frédéric Chapoton
Reviewer(s): Jori Mäntysalo
  • Loading branch information
Release Manager authored and vbraun committed Aug 20, 2016
2 parents b45a575 + 4a3b20f commit 5af72fd
Show file tree
Hide file tree
Showing 20 changed files with 44 additions and 179 deletions.
2 changes: 1 addition & 1 deletion src/sage/algebras/letterplace/free_algebra_letterplace.pyx
Expand Up @@ -833,7 +833,7 @@ cdef class FreeAlgebra_letterplace(Algebra):
if not D:
return self.zero()
cdef int l
for e in D.iterkeys():
for e in D:
l = len(e)
break
cdef dict out = {}
Expand Down
8 changes: 4 additions & 4 deletions src/sage/categories/category_cy_helper.pyx
Expand Up @@ -110,8 +110,8 @@ cpdef tuple _flatten_categories(categories, ClasscallMetaclass JoinCategory):

cdef bint is_supercategory_of_done(new_cat, dict done):
# This is a helper function. It replaces the closure
# any(cat.is_subcategory(new_cat) for cat in done.iterkeys())
for cat in done.iterkeys():
# any(cat.is_subcategory(new_cat) for cat in done)
for cat in done:
if cat.is_subcategory(new_cat):
return True
return False
Expand Down Expand Up @@ -193,7 +193,7 @@ cpdef tuple join_as_tuple(tuple categories, tuple axioms, tuple ignore_axioms):
new_axioms.add(axiom)

# Mark old categories with new axioms as todo
for category in done.iterkeys():
for category in done:
for axiom in new_axioms:
todo.add( (category, axiom) )
for new_cat in new_cats:
Expand All @@ -205,7 +205,7 @@ cpdef tuple join_as_tuple(tuple categories, tuple axioms, tuple ignore_axioms):
for axiom in axiomsS.difference(axs):
todo.add( (new_cat, axiom) )

return _sort_uniq(done.iterkeys())
return _sort_uniq(done)


#############################################
Expand Down
2 changes: 1 addition & 1 deletion src/sage/coding/codecan/codecan.pyx
Expand Up @@ -297,7 +297,7 @@ cdef class InnerGroup:
factor = d.get(self.get_rep(i))
if factor and not factor.is_zero():
m.rescale_row(i, factor)
for i in d.iterkeys():
for i in d:
first_nz_rep = self.join_rows(first_nz_rep, i)
# rescale the already fixed part by column multiplications
for col in fixed_minimized_cols:
Expand Down
141 changes: 3 additions & 138 deletions src/sage/combinat/finite_state_machine.py
Expand Up @@ -4696,7 +4696,7 @@ def latex_options(self,
self.format_transition_label = format_transition_label

if loop_where is not None:
permissible = list(tikz_automata_where.iterkeys())
permissible = list(tikz_automata_where)
for state in self.states():
if hasattr(loop_where, '__call__'):
where = loop_where(state.label())
Expand All @@ -4715,7 +4715,7 @@ def latex_options(self,
(state.label(), permissible))

if initial_where is not None:
permissible = list(tikz_automata_where.iterkeys())
permissible = list(tikz_automata_where)
for state in self.iter_initial_states():
if hasattr(initial_where, '__call__'):
where = initial_where(state.label())
Expand Down Expand Up @@ -4746,7 +4746,7 @@ def latex_options(self,
self.accepting_distance = accepting_distance

if accepting_where is not None:
permissible = list(tikz_automata_where.iterkeys())
permissible = list(tikz_automata_where)
for state in self.iter_final_states():
if hasattr(accepting_where, '__call__'):
where = accepting_where(state.label())
Expand Down Expand Up @@ -14945,7 +14945,6 @@ def result(self, format_output=None):
return self._finished_
return [r[:2] + (format_output(r[2]),) for r in self._finished_]


def preview_word(self, track_number=None, length=1, return_word=False):
"""
Reads a word from the input tape.
Expand Down Expand Up @@ -15000,140 +14999,6 @@ def preview_word(self, track_number=None, length=1, return_word=False):
track_number, length, return_word)


@property
def current_state(self):
"""
The current/reached state in the process.

.. WARNING::

This attribute is deprecated and should not be used any
longer (it may return a wrong result for non-deterministic
finite state machines).

TESTS::

sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},
....: initial_states=['A'], final_states=['A'])
sage: it = inverter.iter_process(input_tape=[0, 1, 1])
sage: for current in it:
....: s = it.current_state
....: print(current)
....: print('current state: {}'.format(s))
doctest:...: DeprecationWarning: This attribute will be
removed in future releases. Use result() at the end of our
iteration or the output of next().
See http://trac.sagemath.org/16538 for details.
process (1 branch)
+ at state 'A'
+-- tape at 1, [[1]]
current state: 'A'
process (1 branch)
+ at state 'A'
+-- tape at 2, [[1, 0]]
current state: 'A'
process (1 branch)
+ at state 'A'
+-- tape at 3, [[1, 0, 0]]
current state: 'A'
process (0 branches)
current state: None
"""
from sage.misc.superseded import deprecation
deprecation(16538, 'This attribute will be removed in future '
'releases. Use result() at the end of our '
'iteration or the output of next().')
if not self._current_:
return None
return next(next(self._current_.itervalues()).iterkeys())


@property
def output_tape(self):
"""
The written output.

.. WARNING::

This attribute is deprecated and should not be used any
longer (it may return a wrong result for non-deterministic
finite state machines).

TESTS::

sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},
....: initial_states=['A'], final_states=['A'])
sage: it = inverter.iter_process(input_tape=[0, 1, 1])
sage: for current in it:
....: t = it.output_tape
....: print(current)
....: print('output: {}'.format(t))
doctest:...: DeprecationWarning: This attribute will be removed
in future releases. Use result() at the end of our iteration
or the output of next().
See http://trac.sagemath.org/16538 for details.
process (1 branch)
+ at state 'A'
+-- tape at 1, [[1]]
output: [1]
process (1 branch)
+ at state 'A'
+-- tape at 2, [[1, 0]]
output: [1, 0]
process (1 branch)
+ at state 'A'
+-- tape at 3, [[1, 0, 0]]
output: [1, 0, 0]
process (0 branches)
output: None
"""
from sage.misc.superseded import deprecation
deprecation(16538, 'This attribute will be removed in future '
'releases. Use result() at the end of our iteration '
'or the output of next().')
if not self._current_:
return None
return next(next(self._current_.itervalues()).itervalues()).outputs[0]


@property
def accept_input(self):
"""
Is ``True`` if the reached state is accepted. This is only available
at the end of the iteration process.

.. WARNING::

This attribute is deprecated and should not be used any
longer (it may return a wrong result for non-deterministic
finite state machines).

TESTS::

sage: inverter = Transducer({'A': [('A', 0, 1), ('A', 1, 0)]},
....: initial_states=['A'], final_states=['A'])
sage: it = inverter.iter_process(input_tape=[0, 1, 1])
sage: for _ in it:
....: pass
sage: it.result()
[Branch(accept=True, state='A', output=[1, 0, 0])]
sage: it.accept_input
doctest:...: DeprecationWarning: This attribute will be removed
in future releases. Use result() at the end of our iteration
or the output of next().
See http://trac.sagemath.org/16538 for details.
True
"""
from sage.misc.superseded import deprecation
deprecation(16538, 'This attribute will be removed in future '
'releases. Use result() at the end of our iteration '
'or the output of next().')
try:
return self._finished_[0].accept
except KeyError:
raise AttributeError


#*****************************************************************************


Expand Down
2 changes: 1 addition & 1 deletion src/sage/combinat/finite_state_machine_generators.py
Expand Up @@ -1977,7 +1977,7 @@ def f(n):
if carry >= 0},
multiedges=False)

initial_values_set = set(initial_values.iterkeys())
initial_values_set = set(initial_values)

missing_initial_values = required_initial_values.difference(
initial_values_set)
Expand Down
4 changes: 3 additions & 1 deletion src/sage/combinat/integer_lists/invlex.pyx
Expand Up @@ -29,6 +29,8 @@ limitations and lack of robustness w.r.t. input.
#*****************************************************************************
from __future__ import print_function

from builtins import object

from sage.misc.classcall_metaclass import ClasscallMetaclass, typecall
from sage.misc.cachefunc import cached_method
from sage.combinat.integer_lists.base cimport IntegerListsBackend
Expand Down Expand Up @@ -1285,7 +1287,7 @@ class IntegerListsLexIter(object):
self._current_sum -= self._current_list[-1]
self._current_list.pop()
def next(self):
def __next__(self):
r"""
Return the next element in the iteration.
Expand Down
4 changes: 2 additions & 2 deletions src/sage/dynamics/interval_exchanges/template.py
Expand Up @@ -3313,7 +3313,7 @@ def __iter__(self):
H(0, 0)
H(0, 0)
"""
for data in self._succ.iterkeys():
for data in self._succ:
yield self._vertex_to_permutation(data)

def __contains__(self, element):
Expand All @@ -3335,7 +3335,7 @@ def __contains__(self, element):
sage: q in s
True
"""
for p in self._succ.iterkeys():
for p in self._succ:
if self._vertex_to_permutation(p) == element:
return True

Expand Down
2 changes: 1 addition & 1 deletion src/sage/graphs/base/c_graph.pyx
Expand Up @@ -1846,7 +1846,7 @@ cdef class CGraphBackend(GenericGraphBackend):
"""
cdef int i
if verts is None:
S = set(self.vertex_ints.iterkeys())
S = set(self.vertex_ints)
for i in range((<CGraph>self._cg).active_vertices.size):
if (i not in self.vertex_labels and
bitset_in((<CGraph>self._cg).active_vertices, i)):
Expand Down
18 changes: 9 additions & 9 deletions src/sage/graphs/generic_graph.py
Expand Up @@ -9776,7 +9776,7 @@ def vertex_iterator(self, vertices=None):
100000 loops, best of 3: 8.85 [micro]s per loop
sage: timeit V = list(P.vertex_iterator()) # not tested
100000 loops, best of 3: 5.74 [micro]s per loop
sage: timeit V = list(P._nxg.adj.iterkeys()) # not tested
sage: timeit V = list(P._nxg.adj) # not tested
100000 loops, best of 3: 3.45 [micro]s per loop

In other words, if you want a fast vertex iterator, call the
Expand Down Expand Up @@ -9855,7 +9855,7 @@ def vertices(self, key=None):
100000 loops, best of 3: 8.85 [micro]s per loop
sage: timeit V = list(P.vertex_iterator()) # not tested
100000 loops, best of 3: 5.74 [micro]s per loop
sage: timeit V = list(P._nxg.adj.iterkeys()) # not tested
sage: timeit V = list(P._nxg.adj) # not tested
100000 loops, best of 3: 3.45 [micro]s per loop

We illustrate various ways to use a ``key`` to sort the list::
Expand Down Expand Up @@ -17341,14 +17341,14 @@ def _color_by_label(self, format='hex', as_function=False, default_color = "blac
The default output is a dictionary assigning edges to colors::

sage: G._color_by_label()
{'#0000ff': [((1,3,2,4), (1,4)(2,3), 3), ..., ((1,3), (1,4,3), 3)],
'#00ff00': [((1,3,2,4), (1,2,4), 2), ..., ((1,3), (1,2,3), 2)],
'#ff0000': [((1,3,2,4), (1,3)(2,4), 1), ..., ((1,3), (1,3,2), 1)]}
{'#0000ff': [((1,3,2,4), (1,4)(2,3), 3), ...],
'#00ff00': [((1,3,2,4), (1,2,4), 2), ...],
'#ff0000': [((1,3,2,4), (1,3)(2,4), 1), ...]}

sage: G._color_by_label({1: "blue", 2: "red", 3: "green"})
{'blue': [((1,3,2,4), (1,3)(2,4), 1), ..., ((1,3), (1,3,2), 1)],
'green': [((1,3,2,4), (1,4)(2,3), 3), ..., ((1,3), (1,4,3), 3)],
'red': [((1,3,2,4), (1,2,4), 2), ..., ((1,3), (1,2,3), 2)]}
{'blue': [((1,3,2,4), (1,3)(2,4), 1), ...],
'green': [((1,3,2,4), (1,4)(2,3), 3), ...],
'red': [((1,3,2,4), (1,2,4), 2), ...]}

TESTS:

Expand Down Expand Up @@ -19831,7 +19831,7 @@ def relabel(self, perm=None, inplace=True, return_map=False, check_input = True,
if len(set(perm.values())) < len(perm):
raise NotImplementedError("Non injective relabeling")

for v in perm.iterkeys():
for v in perm:
if v in self:
try:
hash(perm[v])
Expand Down
6 changes: 3 additions & 3 deletions src/sage/graphs/graph.py
Expand Up @@ -5499,7 +5499,7 @@ def cliques_number_of(self, vertices=None, cliques=None):
{0: 1, 1: 1, 2: 1, 3: 1, 4: 2}
sage: F = graphs.Grid2dGraph(2,3)
sage: X = F.cliques_number_of()
sage: for v in sorted(X.iterkeys()):
sage: for v in sorted(X):
....: print("{} {}".format(v, X[v]))
(0, 0) 2
(0, 1) 3
Expand Down Expand Up @@ -5992,7 +5992,7 @@ def cliques_vertex_clique_number(self, algorithm="cliquer", vertices=None,
{0: 2, 1: 4, 2: 4, 3: 4, 4: 4}
sage: F = graphs.Grid2dGraph(2,3)
sage: X = F.cliques_vertex_clique_number(algorithm="networkx")
sage: for v in sorted(X.iterkeys()):
sage: for v in sorted(X):
....: print("{} {}".format(v, X[v]))
(0, 0) 2
(0, 1) 2
Expand Down Expand Up @@ -6056,7 +6056,7 @@ def cliques_containing_vertex(self, vertices=None, cliques=None):
{0: [[0, 4]], 1: [[1, 2, 3, 4]], 2: [[1, 2, 3, 4]], 3: [[1, 2, 3, 4]], 4: [[0, 4], [1, 2, 3, 4]]}
sage: F = graphs.Grid2dGraph(2,3)
sage: X = F.cliques_containing_vertex()
sage: for v in sorted(X.iterkeys()):
sage: for v in sorted(X):
....: print("{} {}".format(v, X[v]))
(0, 0) [[(0, 1), (0, 0)], [(1, 0), (0, 0)]]
(0, 1) [[(0, 1), (0, 0)], [(0, 1), (0, 2)], [(0, 1), (1, 1)]]
Expand Down
6 changes: 3 additions & 3 deletions src/sage/groups/perm_gps/partn_ref/refinement_graphs.pyx
Expand Up @@ -91,7 +91,7 @@ def isomorphic(G1, G2, partn, ordering2, dig, use_indicator_function, sparse=Fal
G_in = copy(G_in)
to = G_in.relabel(return_map=True)
frm = {}
for v in to.iterkeys():
for v in to:
frm[to[v]] = v
if first:
partition = [[to[v] for v in cell] for cell in partn]
Expand Down Expand Up @@ -382,7 +382,7 @@ def search_tree(G_in, partition, lab=True, dig=False, dict_rep=False, certificat
G_in = copy(G_in)
to = G_in.relabel(return_map=True)
frm = {}
for v in to.iterkeys():
for v in to:
frm[to[v]] = v
partition = [[to[v] for v in cell] for cell in partition]
else:
Expand Down Expand Up @@ -459,7 +459,7 @@ def search_tree(G_in, partition, lab=True, dig=False, dict_rep=False, certificat
return_tuple = [list_of_gens]
if dict_rep:
ddd = {}
for v in frm.iterkeys():
for v in frm:
ddd[frm[v]] = v if v != 0 else n
return_tuple.append(ddd)
if lab:
Expand Down
2 changes: 1 addition & 1 deletion src/sage/libs/gap/util.pyx
Expand Up @@ -134,7 +134,7 @@ cdef void gasman_callback():
Callback before each GAP garbage collection
"""
global owned_objects_refcount
for obj in owned_objects_refcount.iterkeys():
for obj in owned_objects_refcount:
libGAP_MARK_BAG((<ObjWrapper>obj).value)


Expand Down
2 changes: 1 addition & 1 deletion src/sage/matroids/circuit_closures_matroid.pyx
Expand Up @@ -159,7 +159,7 @@ cdef class CircuitClosuresMatroid(Matroid):
else:
self._groundset = frozenset(groundset)
self._circuit_closures = {}
for k in circuit_closures.iterkeys():
for k in circuit_closures:
self._circuit_closures[k] = frozenset([frozenset(X) for X in circuit_closures[k]])
self._matroid_rank = self.rank(self._groundset)

Expand Down

0 comments on commit 5af72fd

Please sign in to comment.