[RFC] Parametric Polymorphism

Diez B. Roggisch deets at nospam.web.de
Sun Sep 25 06:15:46 EDT 2005


Catalin Marinas wrote:
> Hi,
> 
> Sorry if this was previously discussed but it's something I miss in
> Python. I get around this using isinstance() but it would be cleaner
> to have separate functions with the same name but different argument
> types. I think the idea gets quite close to the Lisp/CLOS
> implementation of methods.
> 
> Below is just simple implementation example (and class functions are
> not supported) but it can be further extended/optimised/modified for
> better type detection like issubclass() etc. The idea is similar to
> the @accepts decorator:
> 
> 
> methods = dict()
> 
> def method(*types):
>     def build_method(f):
>         assert len(types) == f.func_code.co_argcount
> 
>         if not f.func_name in methods:
>             methods[f.func_name] = dict()
>         methods[f.func_name][str(types)] = f
> 
>         def new_f(*args, **kwds):
>             type_str = str(tuple([type(arg) for arg in args]))
>             assert type_str in methods[f.func_name]
>             return methods[f.func_name][type_str](*args, **kwds)
>         new_f.func_name = f.func_name
> 
>         return new_f
> 
>     return build_method
> 
> 
> And its utilisation:
> 
> @method(int)
> def test(arg):
>     print 'int', arg
> 
> @method(float)
> def test(arg):
>     print 'float', arg
> 
> test(1)                         # succeeds
> test(1.5)                       # succeeds
> test(1, 2)                      # assert fails
> test('aaa')                     # assert fails
> 
> 
> Let me know what you think. Thanks.

google for gnosis utils and multimethods to see a more "oldfashioned" 
implementation. But your approach certainly is interesting - however, I 
_rarely_ need such functionality. Ususally duck-typing suits me well.

Regards,

Diez



More information about the Python-list mailing list