Types in Python (was: managed lists?)

Ben Finney bignose+hates-spam at benfinney.id.au
Mon May 21 20:28:01 EDT 2007


"Jorgen Bodde" <jorgen.maillist at gmail.com> writes:

> I still have to get used to the lack of (strong) types,

Python does not have weak types, it has strong types. An object knows
its type, and the rules on coercion to other types are minimal and
well-defined.

Python does not have static typing, it has dynamic typing. A name can
be bound and re-bound to any type of object through the lifetime of
the program.

    <URL:http://www.artima.com/weblogs/viewpost.jsp?thread=7590>

or do a web search for: weak strong dynamic static python

> 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..

I'm not sure what you mean here. The exception raised should say what
the problem is; can you give an example of what you're talking about?

> 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.

> It was quite easy to create it, but I wonder if there is already a
> standard solution for lists that carry only objects of a single
> type?

Wrap the code that *uses* that list in a 'try: ... except FooError:'
structure, to catch and report errors when the objects in the list
don't exhibit the correct behaviour.

This way, if Frank extends a totally unrelated type so that it behaves
as your code expects (e.g. has the appropriate attributes, has methods
that respond appropriately), he can insert objects of that type into
the list and it will work correctly.

> I solved it now, by using isinstance() and giving the class name as
> argument to the list

This breaks polymorphism: objects of the type Frank created will fail
this test, even though they will work perfectly well without that
heavy-handed isinstance() restriction.

> (thank god that everything in Python is an object ;-) ) where I
> check against when adding, but re-inventing the wheel is silly
> ofcourse

Indeed. Hopefully you will allow for polymorphism in your code.

-- 
 \      "Probably the earliest flyswatters were nothing more than some |
  `\   sort of striking surface attached to the end of a long stick."  |
_o__)                                                   -- Jack Handey |
Ben Finney



More information about the Python-list mailing list