Mercurial > hg > WSGraph
annotate wsgraph/model.py @ 9:0affca1f4dc0
start using deepcopy since lord knows we cant trust users
author | Jeff Hammel <jhammel@mozilla.com> |
---|---|
date | Mon, 10 Dec 2012 17:10:50 -0800 |
parents | f1f7a505e0d0 |
children | 81d68388ec97 |
rev | line source |
---|---|
0 | 1 from abc import abstractmethod |
9
0affca1f4dc0
start using deepcopy since lord knows we cant trust users
Jeff Hammel <jhammel@mozilla.com>
parents:
8
diff
changeset
|
2 from copy import deepcopy |
8 | 3 from utils import iterable |
0 | 4 |
5 class GraphModel(object): | |
6 | |
7 @abstractmethod | |
8 def node(self, name, **values): | |
9 """get or set a node""" | |
10 | |
11 @abstractmethod | |
12 def nodes(self): | |
13 """returns a list of all nodes""" | |
14 | |
15 @abstractmethod | |
16 def edges(self): | |
17 """returns a list of all edges""" | |
18 | |
19 @abstractmethod | |
20 def edge(self, node1, node2, **values): | |
21 """returns edge from node1 to node2""" | |
22 | |
23 def __getitem__(self, key): | |
24 """ | |
25 if key is a basestring, return the node of that name; | |
26 if key is a 2-tuple/list, return the edge of that name | |
27 """ | |
28 | |
8 | 29 if isinstance(key, basestring) or (not iterable(key)): |
30 return self.node(key) | |
31 else: | |
32 return self.edge(*key) | |
33 | |
34 def __contains__(self, key): | |
35 """ | |
36 if key is ..., returns if that node is in the graph | |
37 if key is a 2-tuple/list, returns if the edge is in the graph | |
38 """ | |
39 # XXX not necessarily the best implementation! | |
40 if isinstance(key, basestring) or (not iterable(key)): | |
41 return key in self.nodes() | |
42 else: | |
43 return tuple(key) in self.edges() | |
0 | 44 |
45 class MemoryCache(GraphModel): | |
46 | |
47 def __init__(self): | |
48 self._edges = {} | |
49 self._nodes = {} | |
50 | |
51 def node(self, name, **values): | |
52 if values: | |
53 # setter | |
9
0affca1f4dc0
start using deepcopy since lord knows we cant trust users
Jeff Hammel <jhammel@mozilla.com>
parents:
8
diff
changeset
|
54 self._nodes[name] = deepcopy(values) |
0 | 55 else: |
56 # getter | |
9
0affca1f4dc0
start using deepcopy since lord knows we cant trust users
Jeff Hammel <jhammel@mozilla.com>
parents:
8
diff
changeset
|
57 # TODO: deepcopy |
0 | 58 return self._nodes.get(name, None) |
59 | |
60 def nodes(self): | |
61 return self._nodes.keys() | |
62 | |
63 def edge(self, node1, node2, **values): | |
64 if values: | |
65 # setter | |
9
0affca1f4dc0
start using deepcopy since lord knows we cant trust users
Jeff Hammel <jhammel@mozilla.com>
parents:
8
diff
changeset
|
66 self._edges[(node1, node2)] = deepcopy(values) |
0 | 67 else: |
68 # getter | |
9
0affca1f4dc0
start using deepcopy since lord knows we cant trust users
Jeff Hammel <jhammel@mozilla.com>
parents:
8
diff
changeset
|
69 # TODO: deepcopy |
0 | 70 return self._edges.get((node1, node2), None) |
71 | |
72 def edges(self): | |
73 return self._edges.keys() |