anonymous function?

F

flupke

Hi,

i'm not sure what the exact type of function is called
for what i'm trying to do but here goes:

------ code -----
def OnClick(self, event):
...
elif ( id == ID_BUTTON_CHECK ):
if __debug__: print " Check pushed"
minutes = self.check_time.GetValue()
t = None
if ( self.check.GetLabel() == "check" ):
if ( minutes != "" ):
self.handleCommand("Check %s minutes\n" % str(minutes))
def sendCheckCommand():
self.connection.message("CHECK")
t = threading.Timer(10.0, sendCheckCommand() )
t.start() printed
self.updateGUI("CHECK_WITH_TIME")
------ code -----

The relevant code being the sendCheckCommand() function declared in the
OnClick function. This code starts a timer that should execute
self.connection.message("CHECK") every 30 seconds. I think this is an
anonymous (in Java it is) function and is really not meant to be a
"real" class function. But when i execute the code, it works 1 time but
the second time it doesn't work anymore and i get this error:

Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Python23\lib\threading.py", line 436, in __bootstrap
self.run()
File "C:\Python23\lib\threading.py", line 544, in run
self.function(*self.args, **self.kwargs)
TypeError: 'NoneType' object is not callable

How can i accomplish this?

Thanks
Benedict
 
R

Richie Hindle

[Benedict]
t = threading.Timer(10.0, sendCheckCommand() )
...
TypeError: 'NoneType' object is not callable

You are calling the sendCheckCommand function and passing its return value
(None) to threading.Timer(). You should say:
t = threading.Timer(10.0, sendCheckCommand)

instead.
 
B

Benjamin Niemann

t = threading.Timer(10.0, sendCheckCommand() )
This will *execute* sendCheckCommand at this point (what you mean by 'it
works 1 time'), implicitly return None, which is passed to the Timer
constructor, which in turn raises the mentioned exception.
Omit the () to get a reference to the function.
> I think this is an
> anonymous (in Java it is) function and is really not meant to be a
> "real" class function.
I would prefer:
t = threading.Timer(10.0, lambda: self.connection.message("CHECK"))
or for compatibility with older python versions:
t = threading.Timer(10.0, lambda s=self:
s.connection.message("CHECK"))
 
F

flupke

Thanks Richie and Benjamin,

that solved the error i got.
(timer is not yet working correctly but that's for another
thread :) )
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top