[Python-3000] Another overloaded functions usecase
Thomas Dunham
thomas.dunham at gmail.com
Thu May 18 14:12:10 CEST 2006
Talk on overloaded functions seems a bit sparse recently, and as I rather like
the idea I wondered if another usecase would be helpful. I reworked
this from an example published 10 years ago by someone who a couple of
you guys might see at lunchtime.
Say we want to read a text document in RTF and convert to one of many
formats. The gang of four describe a builder pattern to do this, and
their approach requires a class for each type of object to build, and
another for the director. It's likely that you'd ditch the director if
you were writing in Python:
class TEXConverter(TextConverter):
def convertChar(token):
...
builder = TEXConverter()
...
act = dict(
CHAR=builder.convertChar,
FONT=builder.convertFont,
PARA=builder.convertParagraph
)
t = get_token()
act[t.type](t)
Maybe with overloaded functions it could look like this:
target = TEXText()
Font, Para, Char = inputTypes()
...
token = get_token()
convert(token, token.type, target)
...
def convert(token, type:Font, target:TEXText):
...
def convert(token, type:Para, target:TEXText):
...
def convert(token, type:Char, target:TEXText):
...
In the original (written in Dylan) Font, Para, Char are instances, and
it uses == to dispatch on individual objects. I'm suggesting creating
more classes and dispatching on (possibly singleton) instances of
them. (The origonal is here: http://norvig.com/design-patterns/)
I don't think this is as elegant as Norvig's version, but I do like
the way it makes the language do all the dispatching, and looking at
the function prototypes gives a good impression of the type/operation
grid that is somewhat hidden in the single-dispatch version.
Tom
More information about the Python-3000
mailing list