detecting containers during object introspection

Steven Taschuk staschuk at telusplanet.net
Wed Jul 23 14:41:27 EDT 2003


Quoth David C. Fox:
  [...]
> That's one possibility.  My original reaction to it was that requiring 
> developers to write comparison operations for every class whose 
> instances are found in the stored dictionary seemed like overkill.  [...]

It might well be; this really depends on how frequently new types
are introduced to the stored dict.

Note also that it would often be possible to reuse comparison
functions written for other types.  Simple scalar values, for
example, can all use the comparison function
    def cmpstruct_scalar(a, b):
        return type(a) == type(b)
For another example, as you noticed, many (but not all -- see
below) instances of classes can be compared by comparison of their
__dict__s.

The point is that, under the choke-on-unknown-types strategy, in
many cases all the developer has to do when introducing a new type
to the stored dict is to add a line
    new_type: some_existing_comparison_function,
to a registry of type -> comparison function.  Doesn't seem
onerous to me.

  [...]
> 1) type(x) == type(y), and
> 
> 2) one of the following is true:
>     a) type(x) == type({}), and
>        x.keys() and y.keys() match, and
>        for each key, cmp_struct(x[key], y[key]) is true
>     b) type(x) == type([]), and
>        for each pair of items in x and y, cmp_struct returns true
>     c) type(x) == types.InstanceType, and
>        cmp_struct(x.__dict__, y.__dict__) is true
>     d) type(x) is not any of the above

Good idea!  A few things:

This doesn't handle new-style classes -- (c) identifies instances
of classic classes only.  hasattr(x, '__dict__') might be a better
test.

Also (c) doesn't compare the structure of class attributes, since
those are in the class dict, not the instance dict.  (I suppose
for pickling this might not matter, since the class is pickled
just as its name, so changes will automagically be available to
the unpickled instance.)

An extension type written in C might maintain lists or whatnot,
but not expose them as attributes.  This is true of the list and
dict types themselves, for example -- which is why you need
special handling for them above.

Instances of subclasses of list and dict won't be treated as lists
and dicts by (a) and (b) as written.  This is probably desirable
-- such subclasses might have additional structure which needs to
be compared -- but the contents of such instances won't be
compared by the later steps, again because those contents are not
exposed as attributes.

-- 
Steven Taschuk                               staschuk at telusplanet.net
"What I find most baffling about that song is that it was not a hit."
                                          -- Tony Dylan Davis (CKUA)





More information about the Python-list mailing list