Types in Python (was: managed lists?)

Asun Friere afriere at yahoo.co.uk
Mon May 21 23:46:59 EDT 2007


On May 22, 10:28 am, Ben Finney <bignose+hates-s... at benfinney.id.au>
wrote:
> "Jorgen Bodde" <jorgen.maill... at gmail.com> writes:
> > Right now i have a list in a class that I export as a member
> > variable to the outside world, it is a standard list (e.g. [] ) but
> > I wish to have a stronger type checking when adding objects, that
> > only some objects are allowed and others are not.
>
> This is a poor idiom in Python. The object system allows powerful
> polymorphism: the only thing that your application should be checking
> is if the objects *can be used* in a particular way, not that they
> belong to a specific subset of the type hierarchy.

And this very succintly sums up the nature of Python's polymorphism
by interface (duck-typing).  An understanding of this is central to
groking the way typing and OO are done in python.

"Jorgen Bodde" <jorgen.maill... at gmail.com> writes:
> I solved it now, by using isinstance() and giving the class name as
> argument to the list

There may be some situations in which testing for class (or
inheritance) are
appropriate, however in the vast majority of cases doing so is a
mistake.  The
object should itself know what to do in any given situation (or throw
an
exception if it doesn't).  Similarly your program should be responding
to
exceptions rather than checking before hand whether its OK to go on.

Instead of reaching for 'isinstance()' you should probably be using
'try : ... except: ...'

> and it sometimes frustates me to no end that a wrongly given
> argument explodes somewhere deep inside my application without
> giving any clue why it blew up in the first place..

If by 'explode' you mean spitting out feedback (as opposed to
hanging),
you should find at least a few clues.  At the very least, you now know
one of the exceptions your code will need to handle.

Asun




More information about the Python-list mailing list