Imported Upstream version 2008.1+svn1553
[opeanno-debian-packaging.git] / game / util / weakmethod.py
blob16ca2a7514f89bb5975e8b971fa5e2bfb9f4ca74
1 # ###################################################
2 # Copyright (C) 2008 The OpenAnno Team
3 # team@openanno.org
4 # This file is part of OpenAnno.
6 # OpenAnno 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.
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.
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 # ###################################################
22 import new
23 import weakref
25 class WeakMethod(object):
26 def __init__(self, function):
27 if not callable(function):
28 raise ValueError("Function parameter not callable")
30 if isinstance(function, new.instancemethod) and function.im_self is not None:
31 self.function = function.im_func
32 self.instance = weakref.ref(function.im_self)
33 else:
34 self.function = function
35 self.instance = None
37 def __call__(self, *args, **kwargs):
38 if self.instance is None:
39 return self.function(*args, **kwargs)
40 elif self.instance() is not None:
41 return self.function(self.instance(), *args, **kwargs)
42 else:
43 raise ReferenceError
45 def __eq__(self, other):
46 return self.function == other.function and self.instance() == other.instance()
48 def __ne__(self, other):
49 return not self.__eq__(other)