Welcome, guest | Sign In | My Account | Store | Cart

This was written to emulate a flexible version of delegates from the C# language. Default arguments can be set and changed, and default arguments can be totally be replaced by new arguments on-the-fly. The delegate class was primarily written for working with Tkinter.

Python, 43 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
'''Support module for GUI programming.

This module provides access to the Delegate class
that was inspired by the C# programming language.'''

__version__ = 1.1

################################################################################

class Delegate:

    'Delegate(target, *args, **kwargs) -> new delegate'
    
    def __init__(self, target, *args, **kwargs):
        'x.__init__(...) initializes x'
        self.__target = target
        self.__args = args
        self.__kwargs = kwargs
        
    def __call__(self, *args, **kwargs):
        'x.__call__(*args, **kwargs) <==> x(*args, **kwargs)'
        if args or kwargs:
            return self.__target(*args, **kwargs)
        else:
            return self.__target(*self.__args, **self.__kwargs)
        
    def args(self, *args):
        'Sets args called on target.'
        self.__args = args
        return self
        
    def kwargs(self, **kwargs):
        'Sets kwargs called on target.'
        self.__kwargs = kwargs
        return self

################################################################################

if __name__ == '__main__':
    import sys
    print 'Content-Type: text/plain'
    print
    print file(sys.argv[0]).read()

When try to design a GUI with Tkinter, functions sometimes need to be dynamically bound to events with some of the parameters already filled in. Python 2.5 appears to possibly being doing something to solve this problem in with some helpful, new solutions; but until then, delegates may be what some people are currently looking for. The Delegate class basically forms a wrapper around a function and automatically changes how it operates based on whether or not arguments were passed to the wrapper when called. Default arguments and keyword arguments can easily be changed once the Delegate object is created.

1 comment

Luke Plant 17 years, 9 months ago  # | flag

What's wrong with closures, or partial function application? (The function 'partial' doesn't exist in 2.4, but it's not hard to write.)