[Python-Dev] Evil isinstance() (original) (raw)

Alex Martelli aleax@aleax.it
Sun, 31 Mar 2002 20:43:48 +0100


On Saturday 31 March 2002 9:45, Aahz wrote:

""" The problem is that in some cases the init for a class needs to dispatch based on the type of the operand. For example, int() takes both numbers and strings. What should we recommend as "standard practice" for this issue if isinstance() is disrecommended? """

What I recommend, FWIW, until and unless PEP 246 eventuates and makes the world wonderful:

if there's a specifically relevant special-method, such as int is for

int(), you can of course first try getting thearg.int -- if that

fails, or if nothing that relevant applies, you can then proceed with

something along the lines of:

try: thearg+'' except TypeError: pass else: "do the stringlike case here"

try: thearg+0 except TypeError: pass else: "do the numberlike case here"

Why would you want your function to break if called with an instance of UserString, say, or a user-defined number type? Smooth polymorphism is high on the list of Python's strong points -- why break it, when you can preserve this excellent quality?

Alex