Is isinstance always "considered harmful"?

Robert Brewer fumanchu at amor.org
Sun May 15 18:27:20 EDT 2005


Jordan Rastrick wrote:
> Subject: Is isinstance always "considered harmful"?
> 
> Say you're writing,
> in Python, the extend() method for a Linked List version of python's
> builtin list. Its really important to know what kind of iterable youre
> being passed in - because if its another Linked list, and you know it,
> you can connect the two in 0(1) time; whereas any other arbitrary
> iterable is going to take 0(n), as you're just going to have to append
> the items one by one. Is this a case where use of isinstance, to see
> exactly what kind of Iterable you have, can be justified?

I'd say so, definitely.

> There are other solutions I can think of - perhaps the least 
> hideous is factoring out the 0(1), "point last to first" code
> in a separated method, __linkedExtend() or something, and then
> do something similar to the above by using an exception,
> like this:
> 
> def extend(self, elems):
>    try:
>       self.__linkedExtend(elems)
>    catch NotALinkedListError:
>       for elem in elems: self.append(elem)
> 
> I dont know, I don't really like this (although it is more BAFP than
> the first version, so maybe that makes it more Pythonic?).

You've decided to special-case a binary operation based on the type of
*both* objects. Whether you use isinstance or __linkedExtend, you're
still providing a single-dispatch mechanism, which gets uglier in
proportion to the number of types involved. Meh. I'd go with isinstance
for now. Your use case is exactly why it's in the language, IMO.

If the number of types you're special-casing becomes unwieldy, you might
be interested in multiple-dispatch approaches (cf
http://gnosis.cx/publish/programming/charming_python_b12.html) and
generic functions (cf
http://dirtsimple.org/2004/11/generic-functions-have-landed.html).


Robert Brewer
System Architect
Amor Ministries
fumanchu at amor.org

> To me,
> instanceof seems like the infimum of all possible evils in this case.
> 
> It'd be nice if I'd seen the source code for Python's builtin list to
> see if any of these kind of considerations are taken into 
> account there
> (ultra fast array copying in C when extend is called on another list,
> perhaps)? Luckily, one of the great gifts of Python is I can indeed
> look at the source for the entire langauge at any time I want. So I'm
> going to go read it (my first time, how exciting!), and in the
> meantime, I'll let replies start accumulating froma  whole lot of
> people who are a lot smarter and more experience in Python than myself
> :)
> 
> Several-weeks-in-and-still-liking-Python-better-than-any-other
> -previously-learned-language-ly
> yours,
> Jordan Rastrick
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 



More information about the Python-list mailing list