Repository: networkx/networkx

Issue:
_relabel_copy and OrderedGraph
The current behavior of `_relabel_copy()` is somewhat unintuitive for OrderedGraphs, where the nodes in the newly created graph are ordered according to the edge iterator of the original graph, not the node iterator. I think this would be fixed by placing `H.add_nodes_from(mapping.get(n, n) for n in G)` at the beginning of the function.

Discussion:
dschult: Let's go ahead and make the relabel files pep8 compliant.  Our general philosophy is to improve pep8 stuff only when we touch code for other reasons. Sometimes that means only part of a file and sometimes it means the whole file. The key is to make it so the pep8 changes don't swamp the actual changes and they won't here.  I don't change the tests for pep8 very often because it feels like I make the readability worse by adding so many line breaks to keep the code within 80 chars per line. But that's personal preference and depends on the test code your looking at. I'll leave that to you.
Thanks!
jarrodmillman: This is ready to merge.

I rebased on master and made a separate commit for pep8 changes outside of the functions I modified.  I didn't make any new code wraps and took out an existing one in `networkx/tests/test_relabel.py` that I thought was unhelpful in terms of readability.
jarrodmillman: @dschult Ready for merge.

Patch:
diff --git a/networkx/classes/digraph.py b/networkx/classes/digraph.py
index 73a59c30c..2c84b9d35 100644
--- a/networkx/classes/digraph.py
+++ b/networkx/classes/digraph.py
@@ -1124,7 +1124,8 @@ class DiGraph(Graph):
             H.add_edges_from((v, u, deepcopy(d)) for u, v, d
                              in self.edges(data=True))
             H.graph = deepcopy(self.graph)
-            H._node = deepcopy(self._node)
+            for n in self._node:
+                H._node[n] = deepcopy(self._node[n])
         else:
             self._pred, self._succ = self._succ, self._pred
             self._adj = self._succ
diff --git a/networkx/relabel.py b/networkx/relabel.py
index 569ba2c02..9cac3f169 100644
--- a/networkx/relabel.py
+++ b/networkx/relabel.py
@@ -6,10 +6,11 @@
 #    BSD license.
 import networkx as nx
 __author__ = """\n""".join(['Aric Hagberg <aric.hagberg@gmail.com>',
-                           'Pieter Swart (swart@lanl.gov)',
-                           'Dan Schult (dschult@colgate.edu)'])
+                            'Pieter Swart (swart@lanl.gov)',
+                            'Dan Schult (dschult@colgate.edu)'])
 __all__ = ['convert_node_labels_to_integers', 'relabel_nodes']
 
+
 def relabel_nodes(G, mapping, copy=True):
     """Relabel the nodes of the graph G.
 
@@ -76,21 +77,21 @@ def relabel_nodes(G, mapping, copy=True):
     Only the nodes specified in the mapping will be relabeled.
 
     The keyword setting copy=False modifies the graph in place.
-    Relabel_nodes avoids naming collisions by building a 
+    Relabel_nodes avoids naming collisions by building a
     directed graph from ``mapping`` which specifies the order of
     relabelings. Naming collisions, such as a->b, b->c, are ordered
     such that "b" gets renamed to "c" before "a" gets renamed "b".
-    In cases of circular mappings (e.g. a->b, b->a), modifying the 
+    In cases of circular mappings (e.g. a->b, b->a), modifying the
     graph is not possible in-place and an exception is raised.
     In that case, use copy=True.
-    
+
     See Also
     --------
     convert_node_labels_to_integers
     """
     # you can pass a function f(old_label)->new_label
     # but we'll just make a dictionary here regardless
-    if not hasattr(mapping,"__getitem__"):
+    if not hasattr(mapping, "__getitem__"):
         m = dict((n, mapping(n)) for n in G)
     else:
         m = mapping
@@ -131,38 +132,39 @@ def _relabel_inplace(G, mapping):
         try:
             G.add_node(new, **G.node[old])
         except KeyError:
-            raise KeyError("Node %s is not in the graph"%old)
+            raise KeyError("Node %s is not in the graph" % old)
         if multigraph:
             new_edges = [(new, new if old == target else target, key, data)
-                         for (_,target,key,data)
+                         for (_, target, key, data)
                          in G.edges(old, data=True, keys=True)]
             if directed:
                 new_edges += [(new if old == source else source, new, key, data)
-                              for (source, _, key,data)
+                              for (source, _, key, data)
                               in G.in_edges(old, data=True, keys=True)]
         else:
             new_edges = [(new, new if old == target else target, data)
-                         for (_,target,data) in G.edges(old, data=True)]
+                         for (_, target, data) in G.edges(old, data=True)]
             if directed:
-                new_edges += [(new if old == source else source,new,data)
-                              for (source,_,data) in G.in_edges(old, data=True)]
+                new_edges += [(new if old == source else source, new, data)
+                              for (source, _, data) in G.in_edges(old, data=True)]
         G.remove_node(old)
         G.add_edges_from(new_edges)
     return G
 
+
 def _relabel_copy(G, mapping):
     H = G.__class__()
+    H.add_nodes_from(mapping.get(n, n) for n in G)
+    H._node.update(dict((mapping.get(n, n), d.copy()) for n, d in G.node.items()))
     if G.name:
         H.name = "(%s)" % G.name
     if G.is_multigraph():
-        H.add_edges_from( (mapping.get(n1, n1),mapping.get(n2, n2),k,d.copy())
-                          for (n1,n2,k,d) in G.edges(keys=True, data=True))
+        H.add_edges_from((mapping.get(n1, n1), mapping.get(n2, n2), k, d.copy())
+                         for (n1, n2, k, d) in G.edges(keys=True, data=True))
     else:
-        H.add_edges_from( (mapping.get(n1, n1),mapping.get(n2, n2),d.copy())
-                          for (n1, n2, d) in G.edges(data=True))
+        H.add_edges_from((mapping.get(n1, n1), mapping.get(n2, n2), d.copy())
+                         for (n1, n2, d) in G.edges(data=True))
 
-    H.add_nodes_from(mapping.get(n, n) for n in G)
-    H._node.update(dict((mapping.get(n, n), d.copy()) for n,d in G.node.items()))
     H.graph.update(G.graph.copy())
 
     return H
@@ -200,27 +202,27 @@ def convert_node_labels_to_integers(G, first_label=0, ordering="default",
     --------
     relabel_nodes
     """
-    N = G.number_of_nodes()+first_label
+    N = G.number_of_nodes() + first_label
     if ordering == "default":
         mapping = dict(zip(G.nodes(), range(first_label, N)))
     elif ordering == "sorted":
         nlist = sorted(G.nodes())
         mapping = dict(zip(nlist, range(first_label, N)))
     elif ordering == "increasing degree":
-        dv_pairs = [(d,n) for (n,d) in G.degree()]
-        dv_pairs.sort() # in-place sort from lowest to highest degree
-        mapping = dict(zip([n for d,n in dv_pairs], range(first_label, N)))
+        dv_pairs = [(d, n) for (n, d) in G.degree()]
+        dv_pairs.sort()  # in-place sort from lowest to highest degree
+        mapping = dict(zip([n for d, n in dv_pairs], range(first_label, N)))
     elif ordering == "decreasing degree":
-        dv_pairs = [(d,n) for (n,d) in G.degree()]
-        dv_pairs.sort() # in-place sort from lowest to highest degree
+        dv_pairs = [(d, n) for (n, d) in G.degree()]
+        dv_pairs.sort()  # in-place sort from lowest to highest degree
         dv_pairs.reverse()
-        mapping = dict(zip([n for d,n in dv_pairs], range(first_label, N)))
+        mapping = dict(zip([n for d, n in dv_pairs], range(first_label, N)))
     else:
-        raise nx.NetworkXError('Unknown node ordering: %s'%ordering)
+        raise nx.NetworkXError('Unknown node ordering: %s' % ordering)
     H = relabel_nodes(G, mapping)
-    H.name = "("+G.name+")_with_int_labels"
+    H.name = "(" + G.name + ")_with_int_labels"
     # create node attribute with the old label
     if label_attribute is not None:
         nx.set_node_attributes(H, label_attribute,
-                               dict((v,k) for k,v in mapping.items()))
+                               dict((v, k) for k, v in mapping.items()))
     return H


Test patch:
diff --git a/networkx/classes/tests/test_digraph.py b/networkx/classes/tests/test_digraph.py
index b46530e4d..c5b50c720 100644
--- a/networkx/classes/tests/test_digraph.py
+++ b/networkx/classes/tests/test_digraph.py
@@ -1,173 +1,192 @@
 #!/usr/bin/env python
-from nose.tools import *
-import networkx
+
+from nose.tools import assert_equal
+from nose.tools import assert_false
+from nose.tools import assert_true
+from nose.tools import assert_raises
+
+
+import networkx as nx
+from networkx.testing import assert_nodes_equal
 from test_graph import BaseGraphTester, BaseAttrGraphTester, TestGraph
 from test_graph import TestEdgeSubgraph as TestGraphEdgeSubgraph
 
+
 class BaseDiGraphTester(BaseGraphTester):
     def test_has_successor(self):
-        G=self.K3
-        assert_equal(G.has_successor(0,1),True)
-        assert_equal(G.has_successor(0,-1),False)
+        G = self.K3
+        assert_equal(G.has_successor(0, 1), True)
+        assert_equal(G.has_successor(0, -1), False)
 
     def test_successors(self):
-        G=self.K3
-        assert_equal(sorted(G.successors(0)),[1,2])
-        assert_raises((KeyError,networkx.NetworkXError), G.successors,-1)
+        G = self.K3
+        assert_equal(sorted(G.successors(0)), [1, 2])
+        assert_raises((KeyError, nx.NetworkXError), G.successors, -1)
 
     def test_has_predecessor(self):
-        G=self.K3
-        assert_equal(G.has_predecessor(0,1),True)
-        assert_equal(G.has_predecessor(0,-1),False)
+        G = self.K3
+        assert_equal(G.has_predecessor(0, 1), True)
+        assert_equal(G.has_predecessor(0, -1), False)
 
     def test_predecessors(self):
-        G=self.K3
-        assert_equal(sorted(G.predecessors(0)),[1,2])
-        assert_raises((KeyError,networkx.NetworkXError), G.predecessors,-1)
+        G = self.K3
+        assert_equal(sorted(G.predecessors(0)), [1, 2])
+        assert_raises((KeyError, nx.NetworkXError), G.predecessors, -1)
 
     def test_edges(self):
-        G=self.K3
-        assert_equal(sorted(G.edges()),[(0,1),(0,2),(1,0),(1,2),(2,0),(2,1)])
-        assert_equal(sorted(G.edges(0)),[(0,1),(0,2)])
+        G = self.K3
+        assert_equal(sorted(G.edges()), [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)])
+        assert_equal(sorted(G.edges(0)), [(0, 1), (0, 2)])
         assert_equal(sorted(G.edges([0, 1])), [(0, 1), (0, 2), (1, 0), (1, 2)])
-        assert_raises((KeyError,networkx.NetworkXError), G.edges,-1)
+        assert_raises((KeyError, nx.NetworkXError), G.edges, -1)
 
     def test_edges_data(self):
-        G=self.K3
-        all_edges = [(0,1,{}),(0,2,{}),(1,0,{}),(1,2,{}),(2,0,{}),(2,1,{})]
+        G = self.K3
+        all_edges = [(0, 1, {}), (0, 2, {}), (1, 0, {}), (1, 2, {}), (2, 0, {}), (2, 1, {})]
         assert_equal(sorted(G.edges(data=True)), all_edges)
         assert_equal(sorted(G.edges(0, data=True)), all_edges[:2])
         assert_equal(sorted(G.edges([0, 1], data=True)), all_edges[:4])
-        assert_raises((KeyError,networkx.NetworkXError), G.edges, -1, True)
+        assert_raises((KeyError, nx.NetworkXError), G.edges, -1, True)
 
     def test_out_edges(self):
-        G=self.K3
-        assert_equal(sorted(G.out_edges()),
-                     [(0,1),(0,2),(1,0),(1,2),(2,0),(2,1)])
-        assert_equal(sorted(G.out_edges(0)),[(0,1),(0,2)])
-        assert_raises((KeyError,networkx.NetworkXError), G.out_edges,-1)
+        G = self.K3
+        assert_equal(sorted(G.out_edges()), [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)])
+        assert_equal(sorted(G.out_edges(0)), [(0, 1), (0, 2)])
+        assert_raises((KeyError, nx.NetworkXError), G.out_edges, -1)
 
     def test_out_edges_dir(self):
-        G=self.P3
-        assert_equal(sorted(G.out_edges()),[(0, 1), (1, 2)])
-        assert_equal(sorted(G.out_edges(0)),[(0, 1)])
-        assert_equal(sorted(G.out_edges(2)),[])
+        G = self.P3
+        assert_equal(sorted(G.out_edges()), [(0, 1), (1, 2)])
+        assert_equal(sorted(G.out_edges(0)), [(0, 1)])
+        assert_equal(sorted(G.out_edges(2)), [])
 
     def test_out_edges_data(self):
-        G=networkx.DiGraph([(0, 1, {'data' : 0}), (1, 0, {})])
-        assert_equal(sorted(G.out_edges(data=True)), [(0, 1, {'data' : 0}), (1, 0, {})])
-        assert_equal(sorted(G.out_edges(0, data=True)), [(0, 1, {'data' : 0})])
+        G = nx.DiGraph([(0, 1, {'data': 0}), (1, 0, {})])
+        assert_equal(sorted(G.out_edges(data=True)), [(0, 1, {'data': 0}), (1, 0, {})])
+        assert_equal(sorted(G.out_edges(0, data=True)), [(0, 1, {'data': 0})])
         assert_equal(sorted(G.out_edges(data='data')), [(0, 1, 0), (1, 0, None)])
         assert_equal(sorted(G.out_edges(0, data='data')), [(0, 1, 0)])
 
     def test_in_edges_dir(self):
-        G=self.P3
+        G = self.P3
         assert_equal(sorted(G.in_edges()), [(0, 1), (1, 2)])
         assert_equal(sorted(G.in_edges(0)), [])
-        assert_equal(sorted(G.in_edges(2)), [(1,2)])
+        assert_equal(sorted(G.in_edges(2)), [(1, 2)])
 
     def test_in_edges_data(self):
-        G=networkx.DiGraph([(0, 1, {'data' : 0}), (1, 0, {})])
-        assert_equal(sorted(G.in_edges(data=True)), [(0, 1, {'data' : 0}), (1, 0, {})])
-        assert_equal(sorted(G.in_edges(1, data=True)), [(0, 1, {'data' : 0})])
+        G = nx.DiGraph([(0, 1, {'data': 0}), (1, 0, {})])
+        assert_equal(sorted(G.in_edges(data=True)), [(0, 1, {'data': 0}), (1, 0, {})])
+        assert_equal(sorted(G.in_edges(1, data=True)), [(0, 1, {'data': 0})])
         assert_equal(sorted(G.in_edges(data='data')), [(0, 1, 0), (1, 0, None)])
         assert_equal(sorted(G.in_edges(1, data='data')), [(0, 1, 0)])
 
     def test_degree(self):
-        G=self.K3
-        assert_equal(sorted(G.degree()),[(0,4),(1,4),(2,4)])
-        assert_equal(dict(G.degree()),{0:4,1:4,2:4})
+        G = self.K3
+        assert_equal(sorted(G.degree()), [(0, 4), (1, 4), (2, 4)])
+        assert_equal(dict(G.degree()), {0: 4, 1: 4, 2: 4})
         assert_equal(G.degree(0), 4)
-        assert_equal(list(G.degree(iter([0]))), [(0, 4)]) #run through iterator
+        assert_equal(list(G.degree(iter([0]))), [
+                     (0, 4)])  # run through iterator
 
     def test_in_degree(self):
-        G=self.K3
-        assert_equal(sorted(G.in_degree()),[(0,2),(1,2),(2,2)])
-        assert_equal(dict(G.in_degree()),{0:2,1:2,2:2})
+        G = self.K3
+        assert_equal(sorted(G.in_degree()), [(0, 2), (1, 2), (2, 2)])
+        assert_equal(dict(G.in_degree()), {0: 2, 1: 2, 2: 2})
         assert_equal(G.in_degree(0), 2)
-        assert_equal(list(G.in_degree(iter([0]))), [(0, 2)]) #run through iterator
+        assert_equal(list(G.in_degree(iter([0]))), [(0, 2)])  # run through iterator
 
     def test_in_degree_weighted(self):
-        G=self.K3
-        G.add_edge(0,1,weight=0.3,other=1.2)
-        assert_equal(sorted(G.in_degree(weight='weight')),[(0,2),(1,1.3),(2,2)])
-        assert_equal(dict(G.in_degree(weight='weight')),{0:2,1:1.3,2:2})
-        assert_equal(G.in_degree(1,weight='weight'), 1.3)
-        assert_equal(sorted(G.in_degree(weight='other')),[(0,2),(1,2.2),(2,2)])
-        assert_equal(dict(G.in_degree(weight='other')),{0:2,1:2.2,2:2})
-        assert_equal(G.in_degree(1,weight='other'), 2.2)
-        assert_equal(list(G.in_degree(iter([1]),weight='other')), [(1, 2.2)])
+        G = self.K3
+        G.add_edge(0, 1, weight=0.3, other=1.2)
+        assert_equal(sorted(G.in_degree(weight='weight')), [(0, 2), (1, 1.3), (2, 2)])
+        assert_equal(dict(G.in_degree(weight='weight')), {0: 2, 1: 1.3, 2: 2})
+        assert_equal(G.in_degree(1, weight='weight'), 1.3)
+        assert_equal(sorted(G.in_degree(weight='other')), [(0, 2), (1, 2.2), (2, 2)])
+        assert_equal(dict(G.in_degree(weight='other')), {0: 2, 1: 2.2, 2: 2})
+        assert_equal(G.in_degree(1, weight='other'), 2.2)
+        assert_equal(list(G.in_degree(iter([1]), weight='other')), [(1, 2.2)])
 
     def test_out_degree_weighted(self):
-        G=self.K3
-        G.add_edge(0,1,weight=0.3,other=1.2)
-        assert_equal(sorted(G.out_degree(weight='weight')),[(0,1.3),(1,2),(2,2)])
-        assert_equal(dict(G.out_degree(weight='weight')),{0:1.3,1:2,2:2})
-        assert_equal(G.out_degree(0,weight='weight'), 1.3)
-        assert_equal(sorted(G.out_degree(weight='other')),[(0,2.2),(1,2),(2,2)])
-        assert_equal(dict(G.out_degree(weight='other')),{0:2.2,1:2,2:2})
-        assert_equal(G.out_degree(0,weight='other'), 2.2)
+        G = self.K3
+        G.add_edge(0, 1, weight=0.3, other=1.2)
+        assert_equal(sorted(G.out_degree(weight='weight')), [(0, 1.3), (1, 2), (2, 2)])
+        assert_equal(dict(G.out_degree(weight='weight')), {0: 1.3, 1: 2, 2: 2})
+        assert_equal(G.out_degree(0, weight='weight'), 1.3)
+        assert_equal(sorted(G.out_degree(weight='other')), [(0, 2.2), (1, 2), (2, 2)])
+        assert_equal(dict(G.out_degree(weight='other')), {0: 2.2, 1: 2, 2: 2})
+        assert_equal(G.out_degree(0, weight='other'), 2.2)
         assert_equal(list(G.out_degree(iter([0]), weight='other')), [(0, 2.2)])
 
     def test_out_degree(self):
-        G=self.K3
-        assert_equal(sorted(G.out_degree()),[(0,2),(1,2),(2,2)])
-        assert_equal(dict(G.out_degree()),{0:2,1:2,2:2})
+        G = self.K3
+        assert_equal(sorted(G.out_degree()), [(0, 2), (1, 2), (2, 2)])
+        assert_equal(dict(G.out_degree()), {0: 2, 1: 2, 2: 2})
         assert_equal(G.out_degree(0), 2)
         assert_equal(list(G.out_degree(iter([0]))), [(0, 2)])
 
     def test_size(self):
-        G=self.K3
-        assert_equal(G.size(),6)
-        assert_equal(G.number_of_edges(),6)
+        G = self.K3
+        assert_equal(G.size(), 6)
+        assert_equal(G.number_of_edges(), 6)
 
     def test_to_undirected_reciprocal(self):
-        G=self.Graph()
-        G.add_edge(1,2)
-        assert_true(G.to_undirected().has_edge(1,2))
-        assert_false(G.to_undirected(reciprocal=True).has_edge(1,2))
-        G.add_edge(2,1)
-        assert_true(G.to_undirected(reciprocal=True).has_edge(1,2))
+        G = self.Graph()
+        G.add_edge(1, 2)
+        assert_true(G.to_undirected().has_edge(1, 2))
+        assert_false(G.to_undirected(reciprocal=True).has_edge(1, 2))
+        G.add_edge(2, 1)
+        assert_true(G.to_undirected(reciprocal=True).has_edge(1, 2))
 
     def test_reverse_copy(self):
-        G=networkx.DiGraph([(0,1),(1,2)])
-        R=G.reverse()
-        assert_equal(sorted(R.edges()),[(1,0),(2,1)])
-        R.remove_edge(1,0)
-        assert_equal(sorted(R.edges()),[(2,1)])
-        assert_equal(sorted(G.edges()),[(0,1),(1,2)])
+        G = nx.DiGraph([(0, 1), (1, 2)])
+        R = G.reverse()
+        assert_equal(sorted(R.edges()), [(1, 0), (2, 1)])
+        R.remove_edge(1, 0)
+        assert_equal(sorted(R.edges()), [(2, 1)])
+        assert_equal(sorted(G.edges()), [(0, 1), (1, 2)])
 
     def test_reverse_nocopy(self):
-        G=networkx.DiGraph([(0,1),(1,2)])
-        R=G.reverse(copy=False)
-        assert_equal(sorted(R.edges()),[(1,0),(2,1)])
-        R.remove_edge(1,0)
-        assert_equal(sorted(R.edges()),[(2,1)])
-        assert_equal(sorted(G.edges()),[(2,1)])
-
-
-class BaseAttrDiGraphTester(BaseDiGraphTester,BaseAttrGraphTester):
+        G = nx.DiGraph([(0, 1), (1, 2)])
+        R = G.reverse(copy=False)
+        assert_equal(sorted(R.edges()), [(1, 0), (2, 1)])
+        R.remove_edge(1, 0)
+        assert_equal(sorted(R.edges()), [(2, 1)])
+        assert_equal(sorted(G.edges()), [(2, 1)])
+
+    def test_reverse_hashable(self):
+        class Foo(object):
+            pass
+        x = Foo()
+        y = Foo()
+        G = nx.DiGraph()
+        G.add_edge(x, y)
+        assert_nodes_equal(G.nodes(), G.reverse().nodes())
+        assert_equal([(y, x)], list(G.reverse().edges()))
+
+
+class BaseAttrDiGraphTester(BaseDiGraphTester, BaseAttrGraphTester):
     pass
 
 
-class TestDiGraph(BaseAttrDiGraphTester,TestGraph):
+class TestDiGraph(BaseAttrDiGraphTester, TestGraph):
     """Tests specific to dict-of-dict-of-dict digraph data structure"""
+
     def setUp(self):
-        self.Graph=networkx.DiGraph
+        self.Graph = nx.DiGraph
         # build dict-of-dict-of-dict K3
-        ed1,ed2,ed3,ed4,ed5,ed6 = ({},{},{},{},{},{})
-        self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed3, 2: ed4}, 2: {0: ed5, 1:ed6}}
+        ed1, ed2, ed3, ed4, ed5, ed6 = ({}, {}, {}, {}, {}, {})
+        self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed3, 2: ed4}, 2: {0: ed5, 1: ed6}}
         self.k3edges = [(0, 1), (0, 2), (1, 2)]
         self.k3nodes = [0, 1, 2]
         self.K3 = self.Graph()
         self.K3._adj = self.K3._succ = self.k3adj
-        self.K3._pred = {0: {1: ed3, 2: ed5}, 1: {0: ed1, 2: ed6}, 2: {0: ed2, 1:ed4}}
+        self.K3._pred = {0: {1: ed3, 2: ed5}, 1: {0: ed1, 2: ed6}, 2: {0: ed2, 1: ed4}}
         self.K3._node = {}
         self.K3._node[0] = {}
         self.K3._node[1] = {}
         self.K3._node[2] = {}
 
-        ed1,ed2 = ({},{})
+        ed1, ed2 = ({}, {})
         self.P3 = self.Graph()
         self.P3._adj = {0: {1: ed1}, 1: {2: ed2}, 2: {}}
         self.P3._succ = self.P3._adj
@@ -178,48 +197,48 @@ class TestDiGraph(BaseAttrDiGraphTester,TestGraph):
         self.P3._node[2] = {}
 
     def test_data_input(self):
-        G=self.Graph(data={1:[2],2:[1]}, name="test")
-        assert_equal(G.name,"test")
-        assert_equal(sorted(G.adj.items()),[(1, {2: {}}), (2, {1: {}})])
-        assert_equal(sorted(G.succ.items()),[(1, {2: {}}), (2, {1: {}})])
-        assert_equal(sorted(G.pred.items()),[(1, {2: {}}), (2, {1: {}})])
+        G = self.Graph(data={1: [2], 2: [1]}, name="test")
+        assert_equal(G.name, "test")
+        assert_equal(sorted(G.adj.items()), [(1, {2: {}}), (2, {1: {}})])
+        assert_equal(sorted(G.succ.items()), [(1, {2: {}}), (2, {1: {}})])
+        assert_equal(sorted(G.pred.items()), [(1, {2: {}}), (2, {1: {}})])
 
     def test_add_edge(self):
-        G=self.Graph()
-        G.add_edge(0,1)
-        assert_equal(G.adj,{0: {1: {}}, 1: {}})
-        assert_equal(G.succ,{0: {1: {}}, 1: {}})
-        assert_equal(G.pred,{0: {}, 1: {0:{}}})
-        G=self.Graph()
-        G.add_edge(*(0,1))
-        assert_equal(G.adj,{0: {1: {}}, 1: {}})
-        assert_equal(G.succ,{0: {1: {}}, 1: {}})
-        assert_equal(G.pred,{0: {}, 1: {0:{}}})
+        G = self.Graph()
+        G.add_edge(0, 1)
+        assert_equal(G.adj, {0: {1: {}}, 1: {}})
+        assert_equal(G.succ, {0: {1: {}}, 1: {}})
+        assert_equal(G.pred, {0: {}, 1: {0: {}}})
+        G = self.Graph()
+        G.add_edge(*(0, 1))
+        assert_equal(G.adj, {0: {1: {}}, 1: {}})
+        assert_equal(G.succ, {0: {1: {}}, 1: {}})
+        assert_equal(G.pred, {0: {}, 1: {0: {}}})
 
     def test_add_edges_from(self):
-        G=self.Graph()
-        G.add_edges_from([(0,1),(0,2,{'data':3})],data=2)
-        assert_equal(G.adj,{0: {1: {'data':2}, 2: {'data':3}}, 1: {}, 2: {}})
-        assert_equal(G.succ,{0: {1: {'data':2}, 2: {'data':3}}, 1: {}, 2: {}})
-        assert_equal(G.pred,{0: {}, 1: {0: {'data':2}}, 2: {0: {'data':3}}})
+        G = self.Graph()
+        G.add_edges_from([(0, 1), (0, 2, {'data': 3})], data=2)
+        assert_equal(G.adj, {0: {1: {'data': 2}, 2: {'data': 3}}, 1: {}, 2: {}})
+        assert_equal(G.succ, {0: {1: {'data': 2}, 2: {'data': 3}}, 1: {}, 2: {}})
+        assert_equal(G.pred, {0: {}, 1: {0: {'data': 2}}, 2: {0: {'data': 3}}})
 
-        assert_raises(networkx.NetworkXError, G.add_edges_from,[(0,)])  # too few in tuple
-        assert_raises(networkx.NetworkXError, G.add_edges_from,[(0,1,2,3)])  # too many in tuple
-        assert_raises(TypeError, G.add_edges_from,[0])  # not a tuple
+        assert_raises(nx.NetworkXError, G.add_edges_from, [(0,)])  # too few in tuple
+        assert_raises(nx.NetworkXError, G.add_edges_from, [(0, 1, 2, 3)])  # too many in tuple
+        assert_raises(TypeError, G.add_edges_from, [0])  # not a tuple
 
     def test_remove_edge(self):
-        G=self.K3
-        G.remove_edge(0,1)
-        assert_equal(G.succ,{0:{2:{}},1:{0:{},2:{}},2:{0:{},1:{}}})
-        assert_equal(G.pred,{0:{1:{}, 2:{}}, 1:{2:{}}, 2:{0:{},1:{}}})
-        assert_raises((KeyError,networkx.NetworkXError), G.remove_edge,-1,0)
+        G = self.K3
+        G.remove_edge(0, 1)
+        assert_equal(G.succ, {0: {2: {}}, 1: {0: {}, 2: {}}, 2: {0: {}, 1: {}}})
+        assert_equal(G.pred, {0: {1: {}, 2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}})
+        assert_raises((KeyError, nx.NetworkXError), G.remove_edge, -1, 0)
 
     def test_remove_edges_from(self):
-        G=self.K3
-        G.remove_edges_from([(0,1)])
-        assert_equal(G.succ,{0:{2:{}},1:{0:{},2:{}},2:{0:{},1:{}}})
-        assert_equal(G.pred,{0:{1:{}, 2:{}}, 1:{2:{}}, 2:{0:{},1: {}}})
-        G.remove_edges_from([(0,0)]) # silent fail
+        G = self.K3
+        G.remove_edges_from([(0, 1)])
+        assert_equal(G.succ, {0: {2: {}}, 1: {0: {}, 2: {}}, 2: {0: {}, 1: {}}})
+        assert_equal(G.pred, {0: {1: {}, 2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}})
+        G.remove_edges_from([(0, 0)])  # silent fail
 
 
 class TestEdgeSubgraph(TestGraphEdgeSubgraph):
@@ -227,7 +246,7 @@ class TestEdgeSubgraph(TestGraphEdgeSubgraph):
 
     def setup(self):
         # Create a doubly-linked path graph on five nodes.
-        G = networkx.DiGraph(networkx.path_graph(5))
+        G = nx.DiGraph(nx.path_graph(5))
         # Add some node, edge, and graph attributes.
         for i in range(5):
             G.node[i]['name'] = 'node{}'.format(i)
@@ -244,7 +263,7 @@ class TestEdgeSubgraph(TestGraphEdgeSubgraph):
         For more information, see GitHub issue #2370.
 
         """
-        G = networkx.DiGraph()
+        G = nx.DiGraph()
         G.add_edge(0, 1)
         H = G.edge_subgraph([(0, 1)])
         assert_equal(list(H.predecessors(0)), [])
diff --git a/networkx/tests/test_relabel.py b/networkx/tests/test_relabel.py
index 31d25fe90..f99ec7354 100644
--- a/networkx/tests/test_relabel.py
+++ b/networkx/tests/test_relabel.py
@@ -3,153 +3,161 @@ from nose.tools import *
 from networkx import *
 from networkx.convert import *
 from networkx.algorithms.operators import *
-from networkx.generators.classic import barbell_graph,cycle_graph
+from networkx.generators.classic import barbell_graph, cycle_graph
 from networkx.testing import *
 
+
 class TestRelabel():
     def test_convert_node_labels_to_integers(self):
         # test that empty graph converts fine for all options
-        G=empty_graph()
-        H=convert_node_labels_to_integers(G,100)
+        G = empty_graph()
+        H = convert_node_labels_to_integers(G, 100)
         assert_equal(H.name, '(empty_graph(0))_with_int_labels')
         assert_equal(list(H.nodes()), [])
         assert_equal(list(H.edges()), [])
 
-        for opt in ["default", "sorted", "increasing degree",
-                    "decreasing degree"]:
-            G=empty_graph()
-            H=convert_node_labels_to_integers(G,100, ordering=opt)
+        for opt in ["default", "sorted", "increasing degree", "decreasing degree"]:
+            G = empty_graph()
+            H = convert_node_labels_to_integers(G, 100, ordering=opt)
             assert_equal(H.name, '(empty_graph(0))_with_int_labels')
             assert_equal(list(H.nodes()), [])
             assert_equal(list(H.edges()), [])
 
-        G=empty_graph()
-        G.add_edges_from([('A','B'),('A','C'),('B','C'),('C','D')])
-        G.name="paw"
-        H=convert_node_labels_to_integers(G)
+        G = empty_graph()
+        G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'D')])
+        G.name = "paw"
+        H = convert_node_labels_to_integers(G)
         degH = (d for n, d in H.degree())
         degG = (d for n, d in G.degree())
         assert_equal(sorted(degH), sorted(degG))
 
-        H=convert_node_labels_to_integers(G,1000)
+        H = convert_node_labels_to_integers(G, 1000)
         degH = (d for n, d in H.degree())
         degG = (d for n, d in G.degree())
         assert_equal(sorted(degH), sorted(degG))
         assert_nodes_equal(H.nodes(), [1000, 1001, 1002, 1003])
 
-        H=convert_node_labels_to_integers(G,ordering="increasing degree")
+        H = convert_node_labels_to_integers(G, ordering="increasing degree")
         degH = (d for n, d in H.degree())
         degG = (d for n, d in G.degree())
         assert_equal(sorted(degH), sorted(degG))
-        assert_equal(degree(H,0), 1)
-        assert_equal(degree(H,1), 2)
-        assert_equal(degree(H,2), 2)
-        assert_equal(degree(H,3), 3)
+        assert_equal(degree(H, 0), 1)
+        assert_equal(degree(H, 1), 2)
+        assert_equal(degree(H, 2), 2)
+        assert_equal(degree(H, 3), 3)
 
-        H=convert_node_labels_to_integers(G,ordering="decreasing degree")
+        H = convert_node_labels_to_integers(G, ordering="decreasing degree")
         degH = (d for n, d in H.degree())
         degG = (d for n, d in G.degree())
         assert_equal(sorted(degH), sorted(degG))
-        assert_equal(degree(H,0), 3)
-        assert_equal(degree(H,1), 2)
-        assert_equal(degree(H,2), 2)
-        assert_equal(degree(H,3), 1)
+        assert_equal(degree(H, 0), 3)
+        assert_equal(degree(H, 1), 2)
+        assert_equal(degree(H, 2), 2)
+        assert_equal(degree(H, 3), 1)
 
-        H=convert_node_labels_to_integers(G,ordering="increasing degree",
-                                          label_attribute='label')
+        H = convert_node_labels_to_integers(G, ordering="increasing degree",
+                                            label_attribute='label')
         degH = (d for n, d in H.degree())
         degG = (d for n, d in G.degree())
         assert_equal(sorted(degH), sorted(degG))
-        assert_equal(degree(H,0), 1)
-        assert_equal(degree(H,1), 2)
-        assert_equal(degree(H,2), 2)
-        assert_equal(degree(H,3), 3)
+        assert_equal(degree(H, 0), 1)
+        assert_equal(degree(H, 1), 2)
+        assert_equal(degree(H, 2), 2)
+        assert_equal(degree(H, 3), 3)
 
         # check mapping
-        assert_equal(H.node[3]['label'],'C')
-        assert_equal(H.node[0]['label'],'D')
-        assert_true(H.node[1]['label']=='A' or H.node[2]['label']=='A')
-        assert_true(H.node[1]['label']=='B' or H.node[2]['label']=='B')
+        assert_equal(H.node[3]['label'], 'C')
+        assert_equal(H.node[0]['label'], 'D')
+        assert_true(H.node[1]['label'] == 'A' or H.node[2]['label'] == 'A')
+        assert_true(H.node[1]['label'] == 'B' or H.node[2]['label'] == 'B')
 
     def test_convert_to_integers2(self):
-        G=empty_graph()
-        G.add_edges_from([('C','D'),('A','B'),('A','C'),('B','C')])
-        G.name="paw"
-        H=convert_node_labels_to_integers(G,ordering="sorted")
+        G = empty_graph()
+        G.add_edges_from([('C', 'D'), ('A', 'B'), ('A', 'C'), ('B', 'C')])
+        G.name = "paw"
+        H = convert_node_labels_to_integers(G, ordering="sorted")
         degH = (d for n, d in H.degree())
         degG = (d for n, d in G.degree())
         assert_equal(sorted(degH), sorted(degG))
 
-        H=convert_node_labels_to_integers(G,ordering="sorted",
-                                          label_attribute='label')
-        assert_equal(H.node[0]['label'],'A')
-        assert_equal(H.node[1]['label'],'B')
-        assert_equal(H.node[2]['label'],'C')
-        assert_equal(H.node[3]['label'],'D')
+        H = convert_node_labels_to_integers(G, ordering="sorted",
+                                            label_attribute='label')
+        assert_equal(H.node[0]['label'], 'A')
+        assert_equal(H.node[1]['label'], 'B')
+        assert_equal(H.node[2]['label'], 'C')
+        assert_equal(H.node[3]['label'], 'D')
 
     @raises(nx.NetworkXError)
     def test_convert_to_integers_raise(self):
         G = nx.Graph()
-        H=convert_node_labels_to_integers(G,ordering="increasing age")
-
+        H = convert_node_labels_to_integers(G, ordering="increasing age")
 
     def test_relabel_nodes_copy(self):
-        G=empty_graph()
-        G.add_edges_from([('A','B'),('A','C'),('B','C'),('C','D')])
-        mapping={'A':'aardvark','B':'bear','C':'cat','D':'dog'}
-        H=relabel_nodes(G,mapping)
+        G = empty_graph()
+        G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'D')])
+        mapping = {'A': 'aardvark', 'B': 'bear', 'C': 'cat', 'D': 'dog'}
+        H = relabel_nodes(G, mapping)
         assert_nodes_equal(H.nodes(), ['aardvark', 'bear', 'cat', 'dog'])
 
     def test_relabel_nodes_function(self):
-        G=empty_graph()
-        G.add_edges_from([('A','B'),('A','C'),('B','C'),('C','D')])
+        G = empty_graph()
+        G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'D')])
         # function mapping no longer encouraged but works
+
         def mapping(n):
             return ord(n)
-        H=relabel_nodes(G,mapping)
+        H = relabel_nodes(G, mapping)
         assert_nodes_equal(H.nodes(), [65, 66, 67, 68])
 
     def test_relabel_nodes_graph(self):
-        G=Graph([('A','B'),('A','C'),('B','C'),('C','D')])
-        mapping={'A':'aardvark','B':'bear','C':'cat','D':'dog'}
-        H=relabel_nodes(G,mapping)
+        G = Graph([('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'D')])
+        mapping = {'A': 'aardvark', 'B': 'bear', 'C': 'cat', 'D': 'dog'}
+        H = relabel_nodes(G, mapping)
         assert_nodes_equal(H.nodes(), ['aardvark', 'bear', 'cat', 'dog'])
 
+    def test_relabel_nodes_orderedgraph(self):
+        G = OrderedGraph()
+        G.add_nodes_from([1, 2, 3])
+        G.add_edges_from([(1, 3), (2, 3)])
+        mapping = {1: 'a', 2: 'b', 3: 'c'}
+        H = relabel_nodes(G, mapping)
+        assert list(H.nodes) == ['a', 'b', 'c']
+
     def test_relabel_nodes_digraph(self):
-        G=DiGraph([('A','B'),('A','C'),('B','C'),('C','D')])
-        mapping={'A':'aardvark','B':'bear','C':'cat','D':'dog'}
-        H=relabel_nodes(G,mapping,copy=False)
+        G = DiGraph([('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'D')])
+        mapping = {'A': 'aardvark', 'B': 'bear', 'C': 'cat', 'D': 'dog'}
+        H = relabel_nodes(G, mapping, copy=False)
         assert_nodes_equal(H.nodes(), ['aardvark', 'bear', 'cat', 'dog'])
 
     def test_relabel_nodes_multigraph(self):
-        G=MultiGraph([('a','b'),('a','b')])
-        mapping={'a':'aardvark','b':'bear'}
-        G=relabel_nodes(G,mapping,copy=False)
-        assert_nodes_equal(G.nodes(),['aardvark', 'bear'])
-        assert_edges_equal(G.edges(),[('aardvark', 'bear'), ('aardvark', 'bear')])
+        G = MultiGraph([('a', 'b'), ('a', 'b')])
+        mapping = {'a': 'aardvark', 'b': 'bear'}
+        G = relabel_nodes(G, mapping, copy=False)
+        assert_nodes_equal(G.nodes(), ['aardvark', 'bear'])
+        assert_edges_equal(G.edges(), [('aardvark', 'bear'), ('aardvark', 'bear')])
 
     def test_relabel_nodes_multidigraph(self):
-        G=MultiDiGraph([('a','b'),('a','b')])
-        mapping={'a':'aardvark','b':'bear'}
-        G=relabel_nodes(G,mapping,copy=False)
-        assert_nodes_equal(G.nodes(),['aardvark', 'bear'])
-        assert_edges_equal(G.edges(),[('aardvark', 'bear'), ('aardvark', 'bear')])
+        G = MultiDiGraph([('a', 'b'), ('a', 'b')])
+        mapping = {'a': 'aardvark', 'b': 'bear'}
+        G = relabel_nodes(G, mapping, copy=False)
+        assert_nodes_equal(G.nodes(), ['aardvark', 'bear'])
+        assert_edges_equal(G.edges(), [('aardvark', 'bear'), ('aardvark', 'bear')])
 
     def test_relabel_isolated_nodes_to_same(self):
-        G=Graph()
+        G = Graph()
         G.add_nodes_from(range(4))
-        mapping={1:1}
-        H=relabel_nodes(G, mapping, copy=False)
+        mapping = {1: 1}
+        H = relabel_nodes(G, mapping, copy=False)
         assert_nodes_equal(H.nodes(), list(range(4)))
 
     @raises(KeyError)
     def test_relabel_nodes_missing(self):
-        G=Graph([('A','B'),('A','C'),('B','C'),('C','D')])
-        mapping={0:'aardvark'}
-        G=relabel_nodes(G,mapping,copy=False)
+        G = Graph([('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'D')])
+        mapping = {0: 'aardvark'}
+        G = relabel_nodes(G, mapping, copy=False)
 
     def test_relabel_copy_name(self):
-        G=Graph()
+        G = Graph()
         H = relabel_nodes(G, {}, copy=True)
         assert_equal(H.graph, G.graph)
         H = relabel_nodes(G, {}, copy=False)
@@ -161,22 +169,21 @@ class TestRelabel():
         assert_equal(H.graph, G.graph)
 
     def test_relabel_toposort(self):
-        K5=nx.complete_graph(4)
-        G=nx.complete_graph(4)
-        G=nx.relabel_nodes(G,dict( [(i,i+1) for i in range(4)]),copy=False)
-        nx.is_isomorphic(K5,G)
-        G=nx.complete_graph(4)
-        G=nx.relabel_nodes(G,dict( [(i,i-1) for i in range(4)]),copy=False)
-        nx.is_isomorphic(K5,G)
-
+        K5 = nx.complete_graph(4)
+        G = nx.complete_graph(4)
+        G = nx.relabel_nodes(G, dict([(i, i + 1) for i in range(4)]), copy=False)
+        nx.is_isomorphic(K5, G)
+        G = nx.complete_graph(4)
+        G = nx.relabel_nodes(G, dict([(i, i - 1) for i in range(4)]), copy=False)
+        nx.is_isomorphic(K5, G)
 
     def test_relabel_selfloop(self):
         G = nx.DiGraph([(1, 1), (1, 2), (2, 3)])
         G = nx.relabel_nodes(G, {1: 'One', 2: 'Two', 3: 'Three'}, copy=False)
-        assert_nodes_equal(G.nodes(),['One','Three','Two'])
+        assert_nodes_equal(G.nodes(), ['One', 'Three', 'Two'])
         G = nx.MultiDiGraph([(1, 1), (1, 2), (2, 3)])
         G = nx.relabel_nodes(G, {1: 'One', 2: 'Two', 3: 'Three'}, copy=False)
-        assert_nodes_equal(G.nodes(),['One','Three','Two'])
+        assert_nodes_equal(G.nodes(), ['One', 'Three', 'Two'])
         G = nx.MultiDiGraph([(1, 1)])
         G = nx.relabel_nodes(G, {1: 0}, copy=False)
         assert_nodes_equal(G.nodes(), [0])