Python callback functions and static methods

Joris djm300 at gmail.com
Mon Jan 5 18:00:37 CET 2009


Hello,

I'm trying to implement callback functionality in a static class.

I have a feeling that I'm doing something against the Python philosophy and
not some programming error but any help would be appreciated.

First, a piece of proof-of-concept-code:
*
class Data:

    callfunc = None

    @staticmethod
    def setCallBack(callfunc):
        Data.callfunc = callfunc

    @staticmethod
    def OnData(data):
        Data.callfunc(data)

def DataCallback(a):
    print 'I received some data: '+ a

Data.setCallBack(DataCallback)
Data.OnData('I have new data')
*

I have defined a class called Data, which I want to use as a "static" class
(i.e. I will never create an instance of it). (I come from a Java background
so forgive me calling this static)
It contains a class variable and 2 static methods.

I also defined a separate function called DataCallback, which would just
print the data it receives.

The goal of this is to use the Data class as a dispatcher of some chunk of
data to whatever function I would like, settable at run-time.

When executing this script, following error occurs:

*Traceback (most recent call last):
  File "callback.py", line 17, in <module>
    Data.OnData('I have new data')
  File "callback.py", line 11, in OnData
    Data.callfunc(data)
TypeError: unbound method DataCallback() must be called with Data instance
as first argument (got str instance instead)
*
What I don't understand is why Python is expecting me to call the
DataCallback() function with a Data instance. To my understanding, the
DataCallback() function can be called from a static method and thus does not
require any instance.

Can anyone point me in the right direction ?

Thanks,

Joris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090105/7a879145/attachment.html>


More information about the Python-list mailing list