'isa' keyword

Rocco Moretti roccomoretti at hotpop.com
Mon Sep 5 10:36:57 EDT 2005


Colin J. Williams wrote:
> Rocco Moretti wrote:
> 
>> Terry Hancock wrote:
>>
>>> On Thursday 01 September 2005 07:28 am, Fuzzyman wrote:
>>>
>>>> What's the difference between this and ``isinstance`` ?
>>>
>>> I must confess that an "isa" operator sounds like it would
>>> have been slightly nicer syntax than the isinstance() built-in
>>> function. But not enough nicer to change, IMHO.
>>
>> Especially conidering that checking parameters with "isinstance" is 
>> considered bad form with Python's duck typing.
> 
> Could you elaborate on that please?

I'm not sure if you're familiar with duck typing or not, so I'll 
summarize it briefly. (More detail can be found by others in the c.l.py 
archive.)

"Duck typing" takes its name from the expression "If it looks like a 
duck, walks like a duck, and quacks like a duck, it's a duck." That is, 
the essence of an object is not its provenance, but its behaviour. This 
arises in part from Python being dynamically typed - you don't have to 
match the type of an object in order to pass it as a parameter.

For example, say you had a function:

def fun(alist):
     for item in alist:
         doworkon(item)

The intended use of the function is for it to be passed a list, but you 
don't have to pass a list - it works just fine with a tuple, an 
iterator, a generator, a file object, a dictionary, or in fact any user 
defined class - all that's needed is for an appropriately defined 
__iter__ or __getitem__ member.

Now if you use isinstance, you mess that up:

def boring(alist):
     if isinstance(alist, list):
         for item in alist:
             doworkon(item)
     else:
         raise TypeError

This will only work with a bona fide list, and choke on the other 
objects - even objects intended by the programmer to act like a list.

Python functions are much more flexible if you don't go checking if an 
object is of a particular type. It makes things like using proxies, 
wrappers and mock objects much easier.

Best practices in Python call for using a parameter and catching when it 
doesn't behave properly, not prophylactically checking types. Python 
programmers can go months to years without using isinstance. It doesn't 
make sense to make it any easier.

P.S. In the OP's case, where it was desired to distinguish between being 
passed a string and being passed a list of strings, the approach used is 
probably sub-optimal. It would likely be better to have the function 
always take a "list", and convert all the fun('string') calls to 
fun(['string']) calls.



More information about the Python-list mailing list