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()
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.
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.
Static binding is being used for overloaded methods. Dynamic binding is being used for overriding methods. It gives better performance.
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.
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
?!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With