Package horizons :: Package util :: Package python :: Module weakmethodlist
[hide private]
[frames] | no frames]

Source Code for Module horizons.util.python.weakmethodlist

 1  # ################################################### 
 2  # Copyright (C) 2008-2017 The Unknown Horizons Team 
 3  # team@unknown-horizons.org 
 4  # This file is part of Unknown Horizons. 
 5  # 
 6  # Unknown Horizons is free software; you can redistribute it and/or modify 
 7  # it under the terms of the GNU General Public License as published by 
 8  # the Free Software Foundation; either version 2 of the License, or 
 9  # (at your option) any later version. 
10  # 
11  # This program is distributed in the hope that it will be useful, 
12  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
13  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
14  # GNU General Public License for more details. 
15  # 
16  # You should have received a copy of the GNU General Public License 
17  # along with this program; if not, write to the 
18  # Free Software Foundation, Inc., 
19  # 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA 
20  # ################################################### 
21   
22  from horizons.util.python.weakmethod import WeakMethod 
23   
24   
25 -class WeakMethodList(list):
26 """A class that handles zero to n callbacks.""" 27
28 - def __init__(self, callbacks=None):
29 """ 30 @param callbacks: None, a function, a list of functions, or a tuple of functions 31 """ 32 super().__init__() 33 self.append(callbacks)
34
35 - def append(self, callback):
36 """Just like list.append, except it can also handle lists and discards None-values""" 37 if callback is None: 38 pass 39 elif callable(callback): 40 list.append(self, WeakMethod(callback)) 41 elif isinstance(callback, list, tuple): 42 for i in callback: 43 self.append(i) 44 else: 45 assert False
46 47 extend = append 48
49 - def execute(self):
50 """Execute all callbacks. Number of callbacks may be zero to n.""" 51 for callback in self: 52 callback()
53
54 - def remove(self, elem):
55 if not isinstance(elem, WeakMethod): 56 elem = WeakMethod(elem) 57 list.remove(self, elem)
58
59 - def __contains__(self, elem):
60 if isinstance(elem, WeakMethod): 61 return list.__contains__(self, elem) 62 else: 63 return WeakMethod(elem) in self
64
65 - def __str__(self):
66 return str([str(i) for i in self])
67