For loops with explicit indices -- again

Kragen Sitaker kragen at pobox.com
Thu Mar 21 02:56:53 EST 2002


"Armin Rigo" <arigo at ulb.ac.be> writes:
> For example, to decrement all positive integers in a list, modifying
> it in-place:
> 
>     it = iter(lst)
>     for x in it:
>         if x>0:
>             lst[it.count-1] -= 1

I wish people would stop asking for requirements to be added to the
iterator protocol.  I think there are good reasons for compliance with
it to be trivially easy.

Maybe we should start asking for features to be added to variables
instead.  With my tongue firmly in my cheek, I propose the following
new language constructs:

onchange expr: suite --- runs suite whenever the location (variable,
mapping item, sequence item, attribute, whatever) named by 'expr'
changes, like Tcl's variable traces; requires user-implemented
containers to call the new itemchanged(self, itemname) function
whenever an item changes; requires __setattr__ implementations to call
the new attrchanged(self, attrname) function whenever they deem that
an attribute has changed.  Under the covers, this is implemented in
terms of new onitemchange(container, name, thunk) and
onattrchange(object, name, thunk) functions.

onrefcountchange expr: suite --- likewise, but runs suite whenever the
reference count of the value 'expr' presently evaluates to changes.

whentrue expr: suite --- uses the onchange machinery to arrange for
'suite' to be run as soon as 'expr' becomes true (by testing 'expr'
and establishing onchange handlers for every elementary subexpression
of it; obviously this won't work if non-functional functions are
involved)

number_of_times_written(expr) --- looks like a function, but "expr" is
a generalized location, just like the arguments to 'del' or the left
operand of '='.  Returns the number of times the location named by the
expression has changed.

number_of_times_read(expr) --- likewise.

previous_values_of(expr) --- returns a list of all previous values
that had been stored in the location named by 'expr'.

number_of_bytecodes_run_since_last_change(expr) --- self-explanatory.




More information about the Python-list mailing list