Scope troubles with a swap function

Alex Martelli aleaxit at yahoo.com
Fri Aug 10 19:04:32 EDT 2001


"Matthew D. Wood" <woodm at equire.com> wrote in message
news:mailman.997474704.7401.python-list at python.org...
> Ok, so swap works, just like you said it should.  (I'm still mad that I
> didn't see that.)
>
> however, the next project is to write a 'cycle_variables' function (or
> single line like you did before.)
>
> So, this time, we take an arbitrary number of variables, and cycle them
> through.
>
> def cycle (*vars) :
>    print 'Cycling the variables...'
>    vars = list(vars)
>    print vars
>    temp = vars[0]
>    for index in range(len(vars) - 1) :
>        vars[index] = vars[index + 1]
>
>    vars[-1] = temp
>    print vars
>    print 'See, I cycled them!'

def cycle(*vars):
    return vars[1:]+vars[:1]

but this needs to be called in the way you seem to detest:

a,b,c,d=cycle(a,b,c,d)

or, if you don't insist on there being a function, then

a,b,c,d=b,c,d,a


There is no general and reliable way for a Python function to
affect its caller's bindings -- or even check in any way that
the values it's being passed DO come from any bindings in
its caller (one or more of them could be values generated on
the fly, or plucked from elsewhere).  *VALUES* -- that's
what a Python function is passed.  VALUES are bound to
its arguments at the call point.  So, its arguments refer to
values (aka objects), but there's no information regarding
how thows values were obtained -- just references to the
values themselves.  The function gets passed NO information
about what (if any) references composed the expressions
its caller used to compute those values -- just the results
of those expressions.

In other words: given the situations:

    a(2+2)
    a(4)
    a(5-1)
    x=4; a(x)

there is *NO* detectable difference between them AT ALL
from a's viewpoint.  There is NO way a can behave differently
in these cases.  ALL it gets is, its own reference to the
immutable value 4, an int object.  Period.  No more, no less.


Alex






More information about the Python-list mailing list