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()
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
intis a disaster, ruling outlong,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 outunicode?!