Collections of non-arbitrary objects ?

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Jun 26 00:46:24 CEST 2007


walterbyrd <walterbyrd at iname.com> writes:

> >>> a = [1,2,3]
> >>> b = a
> >>> a[1] = 'spam'
>
> Here, I have changed b, without an explicit assignment.

No. Both 'a' and 'b' are names bound to a single object; you're
changing that object. This is a subtle difference, but it's one that
is confusing you in this instance.

> So let's say I have list L, and I have a routine that expects every
> item in L to be a dictionary like: {'name':'joe', 'job':'dev',
> 'pay': min_wage}.

If that routine expects objects of a particular *type*, instead of
objects that exhibit expected *behaviour*, the routine is poorly
designed.

> Not only could the app crash if an incorrect item where inserted
> into L. But the app could crash if an incorrect item were inserted
> in lists X,Y, or Z.

When the routine tries to deal with an object that doesn't behave as
expected, an exception will be raised. If the exception goes uncaught,
then Python will exit and throw the exception to the user; I suppose
you could call this a "crash".

> Of course, you can always work around this by just programming very
> carefully, and doing a lot of error checking. That is always true in
> any language.

Better is to catch the exception at a level where it can be dealt
with; this is usually the same level where those non-conforming
objects were placed in the list to begin with.

> BTW: I think polymorphism is great and all. But it does have (and
> IMO should have) it's limitations. For example, I don't think you
> can divide a string by another string.

Indeed, and you'll get an exception raised if you try. Catch that
exception at a level where there's enough context to make sense of it,
and deal with it in whatever way you see fit.

-- 
 \    "Imagine a world without hypothetical situations."  -- Anonymous |
  `\                                                                   |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list