Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it Pythonic to mimic method overloading?

Tags:

python

Is it pythonic to mimic method overloading as found in statically typed languages? By that I mean writing a function that checks the types of its arguments and behaves differently based on those types.

Here is an example:

class EmployeeCollection(object):
    @staticmethod
    def find(value):
        if isinstance(value, str):
            #find employee by name and return
        elif isinstance(value, int):
            #find employee by employee number and return
        else:
            raise TypeError()
like image 219
hwiechers Avatar asked Sep 04 '10 14:09

hwiechers


People also ask

Can we override method overloading?

No. Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class.

Is method overloading good practice?

You need to be careful while overloading a method in Java, especially after the introduction of autoboxing in Java 5. Poorly overloaded method not only adds confusion among developers who use that but also they are error-prone and leaves your program at compiler's mercy to select proper method.

Which is better method overloading for method overriding?

Static binding is being used for overloaded methods. Dynamic binding is being used for overriding methods. It gives better performance.

Does overloading give better performance compared to overriding?

In the case of performance, method overloading gives better performance when compared to overriding because the binding of overridden methods is being done at runtime. Static binding is happens when method overloaded while dynamic binding happens when method overriding.


1 Answers

Not very Pythonic, except perhaps, in 2.6 or better, if all the checks rely on the new abstract base classes, which are intended in part exactly to facilitate such use. If you ever find yourself typechecking for concrete classes, then you know you're making your code fragile and curtailing its use.

So, for example, checking if you have an instance of numbers.Integral is not too bad -- that new ABC exists in good part exactly to ease such checking. Checking if you have an instance of int is a disaster, ruling out long, gmpy.mpz, and a bazillion other kinds of integer-like numbers, to absolutely no good purpose: never check for concrete classes!

Strings are a difficult case, but the basestring abstract class (not one of the new kind of ABCs) is a possibility. A bit too restrictive, perhaps, but if you're using other ABCs around it, it might kinda, sorta work, if you really have to. Most definitely not str -- why ever rule out unicode?!

like image 66
Alex Martelli Avatar answered Oct 21 '22 20:10

Alex Martelli