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

Source Code for Module horizons.util.python.callback

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 23 -class Callback:
24 """This class basically provides just callbacks with arguments. 25 The same can be achieved via 'lambda: f(arg1, arg2)', but this class has 26 more flexibility; e.g. you can compare callbacks, which can't be done with lambda functions. 27 """
28 - def __init__(self, callback_function, *args, **kwargs):
29 assert callable(callback_function), "Argument to for callback_f is {}".format(callback_function) 30 self.callback = callback_function 31 self.args = args 32 self.kwargs = kwargs
33 34 @staticmethod
35 - def ChainedCallbacks(*args):
36 """Named constructor for callbacks executed in a row. 37 Use Callback objects to pass arguments to the callbacks. 38 It is guaranteed that the callbacks are executed in order. 39 @param args: callables""" 40 callbacks = [Callback(i) for i in args] 41 42 def tmp(): 43 for i in callbacks: 44 i()
45 return Callback(tmp)
46
47 - def __call__(self):
48 return self.callback(*self.args, **self.kwargs)
49
50 - def __eq__(self, other):
51 try: 52 if other.callback == self.callback and \ 53 other.args == self.args and \ 54 other.kwargs == self.kwargs: 55 return True 56 else: 57 return False 58 except AttributeError: 59 return False
60
61 - def __ne__(self, other):
62 return not self.__eq__(other)
63
64 - def __hash__(self):
65 return hash((self.callback, self.args, 66 tuple(self.kwargs.items()))) # to tuple, dict is unhashable
67
68 - def __str__(self):
69 return 'Callback({}, {}, {})'.format(self.callback, self.args, self.kwargs)
70