Collections of non-arbitrary objects ?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Jun 25 00:31:09 EDT 2007


walterbyrd a écrit :
> On Jun 22, 11:43 pm, Ben Finney <bignose+hates-s... at benfinney.id.au>
> wrote:
> 
> 
>>Can you help us understand, by showing a use case that would in your
>>estimation be improved by the feature you're describing?
>>
> 
> 
> Suppose you are sequentially processing a list with a routine that
> expects every item to be of a certain type. 

it should expects every item to support a given protocol (expose a given 
interface, have a given set of attributes, whatever...).

OOP is not about "types" or "classes", it's about objects. And in a 
dynamic language like Python, where you can add/remove/replace almost 
each attribute (including methods and even it's class...) of an object 
at runtime, override the way the attribute look-up is done, etc, this is 
specially true.

The fact that an object is an instance of a given class doesn't 
necessarily imply that it supports the same protocol. And the fact that 
an object is an instance of a given class is only true at a given 
time... So testing on type to allow inclusion of an object in a list for 
"type safety" reasons is mostly a waste of time. It's also 
counter-productive since it would reject objects that actually supports 
the right protocol but are not of the "correct type".

> Something in the list that
> doesn't conform to the type

s/conform to the type/support the protocol/

> could give you unexpected results, maybe
> crash your application.

Yes. But... you do test your application, don't you ?-)

> In python, as far as I know, there is nothing built into the language
> to keep any type of item from being included in a list

No. cf above.

> - or any such
> structure. To me, that seems like a potentially vulnerability.

Did you actually had some effective problem with this ?

> Especially since variables in python do not have to be explicitly
> assigned

???

I suppose you meant something else here, probably about declarative typing ?

> - another variable that points to the same thing, could
> change the data that a variable points to.

Give me a reference to an object in a list, and I can change almost any 
attribute of the object - even it's class.

FWIW, a similar - but usually much much worse wrt/ possible results - 
problem exists in C with pointers and memory.

I came to Python from statically typed languages, and first had a 
similar reaction. It took me some time to believe it, but type errors 
are quite less frequent that you would imagine, and most of the time 
quite trivial to spot and fix. I've had bigger problems with memory 
handling and dangling pointers in C, Pascal or C++.



More information about the Python-list mailing list