variable declaration

Alex Martelli aleaxit at yahoo.com
Tue Feb 1 13:19:15 EST 2005


Michael Tobis <mt at 3planes.com> wrote:
   ...
> I don't know that it's ever necessary to rebind, but it is, in fact,
> common, and perhaps too easy. In numeric Python, avoiding rebinding
> turns out to be a nontrivial skill. 

Well, a for-statement is BASED on rebinding, for example.  Maybe you
don't mean to address rebinding per se, but rebinding in ``separate
statements''?  The ``separation'' needs to be defined carefully to make
while-loops work, too.  Normally, a while-statement's header clause
would be something like:
    while <expression>:
where the expression depends on the values bound to some local
variables.  For the first evaluation, the variables need to be bound by
earlier statements; for the expression to eventually become false, it's
likely (unless we're talking about mutable objects) that the variables
need to be re-bound in the loop body.

For example, consider:

def f(a, b):
    x = 0 
    while x < 100000:
        print x,
        x = a*x + b
    print

would you require the programmer to find out a closed-form expression
for this recurrence relation, in order to avoid having to rebind the
name 'x'?  OK, in this particular case it may be OK, if you are willing
to put competence in college-level algebra as a prerequisite for using
Python.  But what if the rebinding in the body of the loop was to a more
complicated expression on x?  What if it was something like x=g(x)?  I'm
afraid we'd end up with weird constructs such as:

def ff(g):
    x = [0]
    while x[-1] < 100000:
        print x[-1],
        x.append(g(x[-1]))
    print

if we had to avoid rebinding completely.  Or, you could force the
iteration to be changed into a recursion... but then you'd better be
prepared to remove the current 'recursion limit' AND offer tail-call
optimization possibilities, at the very least.

All in all, I fail to see what gains would be expected by making Python
into a single-assignment or single-binding language, even on a module by
module basis, to repay this kind of awkwardness.


Alex



More information about the Python-list mailing list