27
|
1 class ComponentBase(object):
|
|
2 """Component abstract base class
|
|
3
|
|
4 Strictly speaking you do not need to derive from this class to create your
|
|
5 own components, but it does serve to document the full interface that a
|
|
6 component implements and it provides some basic implementations for
|
|
7 certain methods
|
|
8 """
|
|
9
|
|
10 ## Optional attributes and methods ##
|
|
11
|
|
12 def set_manager(self, manager):
|
|
13 """Set the manager of this component. If this method exists it will be
|
|
14 automatically called when the component is added to a manager.
|
|
15
|
|
16 This method stores the manager and allows the component to be added
|
|
17 only once to a single manager.
|
|
18 """
|
|
19 assert getattr(self, 'manager', None) is None, 'Component cannot be added to multiple managers'
|
|
20 self.manager = manager
|
|
21
|
|
22 def __del__(self):
|
|
23 """Break circrefs to allow faster collection"""
|
|
24 if hasattr(self, 'manager'):
|
|
25 del self.manager
|
|
26
|
|
27 ## Mandatory methods ##
|
|
28
|
|
29 def add(self, entity_id, data=None, **data_kw):
|
|
30 """Add a data entry in the component for the given entity. Additional
|
|
31 data (if any) for the entry can be provided in the data argument or as
|
|
32 keyword arguments. Additional data is optional and if omitted then
|
|
33 suitable defaults will be used. Return an entity data object
|
|
34 for the new entity entry.
|
|
35
|
|
36 The semantics of the data arguments is up to the component.
|
|
37
|
|
38 An entity_id is a unique key, thus multiple separate data entries for
|
|
39 a given entity are not allowed. Components can indivdually decide
|
|
40 what to do if an entity_id is added multiple times to the component.
|
|
41 Potential options include, raising an exception, replacing the
|
|
42 existing data or coalescing it somehow.
|
|
43 """
|
|
44
|
|
45 def remove(self, entity_id):
|
|
46 """Remove the entity data entry from the component. If the
|
|
47 entity is not in the component, raise KeyError
|
|
48 """
|
|
49
|
|
50 def __delitem_(self, entity_id):
|
|
51 """Same as remove()"""
|
|
52
|
|
53 def __len__(self):
|
|
54 """Return the number of entities in the component"""
|
|
55 raise NotImplementedError()
|
|
56
|
|
57 def __iter__(self):
|
|
58 """Return an iterator of entity data objects in this component
|
|
59
|
|
60 No order is defined for these data objects
|
|
61 """
|
|
62 raise NotImplementedError()
|
|
63
|
|
64 def __contains__(self, entity_id):
|
|
65 """Return True if the entity is contained in the component"""
|
|
66 raise NotImplementedError()
|
|
67
|
|
68 def __getitem__(self, entity_id):
|
|
69 """Return the entity data object for the given entity.
|
|
70 The entity data object returned may be mutable, immutable or a
|
|
71 mutable copy of the data at the discretion of the component
|
|
72 """
|
|
73 raise NotImplementedError()
|
|
74
|