Function Overloading and Python

Carl Banks pavlovevidence at gmail.com
Mon Feb 25 07:48:41 EST 2008


On Feb 25, 2:33 am, Allen Peloquin <tandonm... at gmail.com> wrote:
> I have a personal project that has an elegant solution that requires
> both true multiple inheritance of classes (which pretty much limits my
> language choices to C++ and Python) and type-based function
> overloading.
>
> Now, while this makes it sound like I have to resign myself to C++,
> which I am not a fan of writing, I have resisted thus far. Who wants
> to manage their own memory? No, I have fallen in love with Python, and
> so come asking for help.
>
> I have a very large multiple inheritance tree that will be frequently
> extended as my project goes on. Let us call these "type A" classes.
>
> I also have a moderately sized single inheritance tree whose task is
> to match sets of "type A" parameters in a function. Let us call these
> "type B" classes. "Type Bs" have one function, which is extended with
> each new child, and overloaded to match varying combinations of "Type
> As." The reason for this is code-reuse and eventual matching with
> common "type A" parents.
>
> Now, what are my options in Python to dispatch unique code based on
> the permutations of "type A" classes without code repetition?
> Such as, where in C++...
>
> class B
> {
>     fun(A x, A y, A z)...
>     fun(A1 x, A y, A z)...
>
> }
>
> class B1
> {
>     fun(A1 x, A y, A z)...
>
> }
>
> Such that any previous behavior is inherited, but behaves
> polymorphically because of the single function name.
>
> B1.fun(A(x), A(y), A(z)) == B.fun(A(x), A(y), A(z))
> but
> B1.fun(A1(x), A(y), A(z) != B.fun(A1(x), A(y), A(z))
>
> Is there a data-structure solution or third party module that would
> mimic this behavior?
>
> PEP 3124 got my hopes up, but I was let down when it was deferred.
>
> Thank you for your time.

At risk of sounding snarky, I'll first advise:

"Use different names for different expected types."

Presumably you know what types you're passing in when you write the
calling function, so you'd also know which variant of the function
you'd be calling.  Might as well just use separate names then.


But you don't want to do that, and you might have good reasons.  So,
secondly I will advise:

"Use different names inside the class, and have one function in the
base class dispatch as necessary."

class B(object):
    def fun(x,y,z):
        if type(x) == "A":
            return _fun_A(x,y,z)
        if type(x) == "A1":
            return _fun_A1(x,y,z)

    def _fun_A(x,y,z):
        # you know x is of type A

    def _fun_A1(x,y,z):
        # you know x is of type A1

class B1(B):
    def _fun_A(x,y,z):
        # overrides B._fun_A


In other words, subclasses only override _fun_type variants.  fun is
left alone.  Extend idea as needed for your needs.



Carl Banks



More information about the Python-list mailing list