polymorphism w/out signatures?

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Thu May 6 16:59:35 EDT 2004


Roy Smith wrote:

> The most common reason is the example you gave, where you want a
> function which will operate on either an item, or a bunch of items. 
> You might want to be able to say:
> 
> nuke ("Perl")
> 
> to get rid of everybody's least favorite language, and also be able to
> pass in a bunch of them:
> 
> nuke (("C++", "Java", "Perl"))
> 
> to get rid of all three at once.  If you really wanted to do that, you
> could define nuke something like:
> 
> def nuke (lang):
>    if isinstance (lang, types.TupleType):
>       for oneLanguage in lang:
>          nuke (oneLanguage)
>    else:
>       whatever
> 
> In general, however, I try to stay away from stuff like that.

A better approach anyway IMO for the above is to either always require
an iterable, or to accept a variable number of parameters i.e.

def nuke (lang, *langs):  # must have at least one parameter
    _nuke(lang1)

    for lang in langs
        _nuke(lang)

I could of course have constructed a combined tuple, but that's silly.

Then you can call the above as any of:

nuke('Perl')
nuke('C++', 'Java', 'Perl')
nuke(*('C++', 'Java', 'Perl'))

Tim Delaney




More information about the Python-list mailing list