[RFC] Parametric Polymorphism

Catalin Marinas catalin.marinas at gmail.com
Sun Sep 25 10:30:30 CEST 2005


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.

--
Catalin



More information about the Python-list mailing list