summaryrefslogtreecommitdiff
path: root/networkx/classes
diff options
context:
space:
mode:
authorStefan van der Walt <stefanv@berkeley.edu>2022-05-07 23:32:25 -0700
committerGitHub <noreply@github.com>2022-05-08 02:32:25 -0400
commit121be2d321dcf4087cb4feb3e428a0bd861bdf7c (patch)
tree7e2ad607cc4b39ed02f40f1aa9d48a7ec09f99bc /networkx/classes
parent4f2b1b854d5934a487b428f252ad6ff9375d74ad (diff)
downloadnetworkx-121be2d321dcf4087cb4feb3e428a0bd861bdf7c.tar.gz
Cache `nodes` property on Graph (#5600)
Diffstat (limited to 'networkx/classes')
-rw-r--r--networkx/classes/graph.py10
-rw-r--r--networkx/classes/tests/test_graph.py4
2 files changed, 7 insertions, 7 deletions
diff --git a/networkx/classes/graph.py b/networkx/classes/graph.py
index 40b061cb..a1e44035 100644
--- a/networkx/classes/graph.py
+++ b/networkx/classes/graph.py
@@ -8,6 +8,7 @@ Self-loops are allowed but multiple edges are not (see MultiGraph).
For directed graphs see DiGraph and MultiDiGraph.
"""
from copy import deepcopy
+from functools import cached_property
import networkx as nx
from networkx.classes.coreviews import AdjacencyView
@@ -658,7 +659,7 @@ class Graph:
except KeyError:
pass
- @property
+ @cached_property
def nodes(self):
"""A NodeView of the Graph as G.nodes or G.nodes().
@@ -749,12 +750,7 @@ class Graph:
{0: 1, 1: 2, 2: 3}
"""
- nodes = NodeView(self)
- # Lazy View creation: overload the (class) property on the instance
- # Then future G.nodes use the existing View
- # setattr doesn't work because attribute already exists
- self.__dict__["nodes"] = nodes
- return nodes
+ return NodeView(self)
def number_of_nodes(self):
"""Returns the number of nodes in the graph.
diff --git a/networkx/classes/tests/test_graph.py b/networkx/classes/tests/test_graph.py
index 3e454c17..19825d3a 100644
--- a/networkx/classes/tests/test_graph.py
+++ b/networkx/classes/tests/test_graph.py
@@ -170,6 +170,10 @@ class BaseGraphTester:
G.add_edge(1, 1)
G.remove_nodes_from([0, 1])
+ def test_nodes_cached(self):
+ G = self.K3.copy()
+ assert id(G.nodes) == id(G.nodes)
+
class BaseAttrGraphTester(BaseGraphTester):
"""Tests of graph class attribute features."""