Finding the type of indexing supported by an object?

Derek Peschel dpeschel at eskimo.com
Sat Aug 26 03:14:56 EDT 2006


In article <1hkii5f.19t6trjthzd67N%aleax at mac.com>, Alex Martelli wrote:
>Derek Peschel <dpeschel at eskimo.com> wrote:

>> They are the same except for the expression in "for key in ...".  Can they
>> be combined into one function?  How can I determine if the argument is
>
>They can easily be refactored, if that's what you mean:

No, that isn't what I mean.  I wanted _one_ function that works with a wide
variety of objects -- anything that has a finite number of keys you can
iterate over, with each key mapping to a finite number of values, and the
key iteration and value lookup referentially transparent.  This hypothetical
function would have to do some checking of the argument type, but hopefully
as little as possible.  It should work with object types invented after it
was written.

Reading everyone's replies, especially yours and Fredrik Lundh's, I realized
I've been thinking of the whole problem in Smalltalk (or possibly Ruby)
terms.  Smalltalk and Ruby use inheritance to describe some properties of
objects.  Python has many primitive types that aren't related to eaach other.
I thought that testing for methods might get the properties I wanted, but
you two pointed out that the method writer has too much latitude.  Do you
think the generic-function idea is still useful?

At the moment I only need to invert dicts and lists.  Is subclassing dict
and list considred good style?  (I see I can't add methods to dict and list
directly.)

>I've also performed a few other minor enhancements (never name things
>dict or list because that hides the builtin types, use xrange vs range).

OK, I'll remember those points.  The argument names are a style I got
from my Ruby code, and possibly not a good idea there either.

>I have not changed the 4 lines in the if/else though I don't like them
>(if not.../else is a very confusing construct -- at a minimum I'd
>rephrase it as if/else swapping the bodies of the two clauses).

It used if/else originally.  Then I swapped the parts of the conditional
to make the inversion function match another function (that takes a key,
old value, and new value, and makes the change in a sequence and in its
inverted form).  To me the swapped version made some sense in the second
function, because of the layout of the function as a whole, but you have
a point that if not/else is rarely (never?) clear.

>If you want to add a generic form accepting either lists or dicts you
>need a try/except statement inside it, e.g.:

Is that a reliable way to get the properties I wanted?

RADLogic Pty. Ltd. added a two-way dict package to the Cheese Shop.  It
requires that the mapping be one-to-one, which won't work for me.  It sub-
classes dict, and requires that keys and values be hashable.

-- Derek



More information about the Python-list mailing list