faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes

Entry

Delayed command class

Jul 5th, 2000 10:00
Nathan Wallace, Hans Nowak, Snippet 124, Timothy R Evans


"""
Packages: miscellaneous
"""
#!/usr/bin/env python
'''
The Command class was written by Tim Evans
This class can be used for delayed execution of functions.  It is very 
useful for Tkinter callbacks or functional programming (map, filter).
The precewdence of keyword args can be changed.  Currently the
keywords passed to the object at creation time provide default values
which are overided if the same keyword is passed to the object when it 
is called.  This can be changed if required.
'''
class Command:
    def __init__(self, func, *args, **kw):
        self.func = func
        self.args = args
        self.kw = kw
    def __call__(self, *args, **kw):
	newkw = self.kw
        newkw.update(kw)
        args = self.args + args
        apply(self.func, args, newkw)
# this is a small demonstration of how to use the Command class
if __name__ == '__main__':
    def echo(*args, **kw):
        print 'args:    ', args
        print 'keywords:', kw
    foo = Command(echo, 'foo', 'bar', wibble='blarg', spam='eggs')
    foo('parrot', parrot='dead', wibble='xxx')