| 
      
      
      From: Magnus L. H. <ma...@he...> - 2004-07-27 16:46:58
      
     | 
| Joerg Lehmann <jo...@us...>:
>
[snip]
> Another typical use of isinstance is to implement some type based
> polymorphism. For instance, if you pass some object to a function and
> this function checks in which way he can deal with this object.
Sure -- but in Python the Right Thing(tm) in most cases isn't
type-base polymorphism, but signature-based polymorphism. If something
quacks like a duck, you treat it like a duck. It doesn't really have
to *be* a duck. (Someone might have implemented a duck-robot, for
example, and it would be impolite not to let them use that instead :)
> Here, I have to admit, I'm not always sure about the Python way of
> doing things like that... A typical example was the constructor of
> the unit.length class (only in the released PyX versions), which was
> able to convert nearly anything to a length. In CVS we already got
> rid of that...
OK, let's take a look at that as an example...
First of all, it uses helper.isstring and helper.isnumber, both of
which use the Leap Before You Look idiom -- I have no quarrels with
them. That is not type checking/type based polymorphism. This is how
it *should* be done <wink>
The only use of isintance here is:
  if isinstance(l, length):
      self.length =3D l.length
  elif helper.isstring(l):
      # ...
Why is this check necessary? Why not use something like this (possibly
wrapped in helper.islength or something, if desired):
  try:
      self.length =3D l.length
  except AttributeError:
      if helper.isstring(l):
          # ...
Then, if I decided to implement my own length-like class which
supplied the required length attribute (which is, after all, all
that's required) it would work nicely.
The only thing you achieve by using isintance instead is to close the
door in my face -- "no wannabe lengths permitted".
Such type-based discrimination <wink> is in most cases necessary; if
an object can do the job, just let it.
(Often, using polymorphism directly, i.e. simply calling a method on
the given object, would be better than using an if statement checking
properties on the object. That's not feasible in special cases such as
this, where you have to deal with numbers and strings and the like, of
course.)
>         J=F6rg
--=20
Magnus Lie Hetland     "Canned Bread: The greatest thing since sliced
http://hetland.org      bread!" [from a can in Spongebob Squarepants]
 |