0
|
1 from abc import abstractmethod
|
8
|
2 from utils import iterable
|
0
|
3
|
|
4 class GraphModel(object):
|
|
5
|
|
6 @abstractmethod
|
|
7 def node(self, name, **values):
|
|
8 """get or set a node"""
|
|
9
|
|
10 @abstractmethod
|
|
11 def nodes(self):
|
|
12 """returns a list of all nodes"""
|
|
13
|
|
14 @abstractmethod
|
|
15 def edges(self):
|
|
16 """returns a list of all edges"""
|
|
17
|
|
18 @abstractmethod
|
|
19 def edge(self, node1, node2, **values):
|
|
20 """returns edge from node1 to node2"""
|
|
21
|
|
22 def __getitem__(self, key):
|
|
23 """
|
|
24 if key is a basestring, return the node of that name;
|
|
25 if key is a 2-tuple/list, return the edge of that name
|
|
26 """
|
|
27
|
8
|
28 if isinstance(key, basestring) or (not iterable(key)):
|
|
29 return self.node(key)
|
|
30 else:
|
|
31 return self.edge(*key)
|
|
32
|
|
33 def __contains__(self, key):
|
|
34 """
|
|
35 if key is ..., returns if that node is in the graph
|
|
36 if key is a 2-tuple/list, returns if the edge is in the graph
|
|
37 """
|
|
38 # XXX not necessarily the best implementation!
|
|
39 if isinstance(key, basestring) or (not iterable(key)):
|
|
40 return key in self.nodes()
|
|
41 else:
|
|
42 return tuple(key) in self.edges()
|
0
|
43
|
|
44 class MemoryCache(GraphModel):
|
|
45
|
|
46 def __init__(self):
|
|
47 self._edges = {}
|
|
48 self._nodes = {}
|
|
49
|
|
50 def node(self, name, **values):
|
|
51 if values:
|
|
52 # setter
|
|
53 self._nodes[name] = values
|
|
54 else:
|
|
55 # getter
|
|
56 return self._nodes.get(name, None)
|
|
57
|
|
58 def nodes(self):
|
|
59 return self._nodes.keys()
|
|
60
|
|
61 def edge(self, node1, node2, **values):
|
|
62 if values:
|
|
63 # setter
|
|
64 self._edges[(node1, node2)] = values
|
|
65 else:
|
|
66 # getter
|
|
67 return self._edges.get((node1, node2), None)
|
|
68
|
|
69 def edges(self):
|
|
70 return self._edges.keys()
|