Scope troubles with a swap function

Steve Holden sholden at holdenweb.com
Fri Aug 10 15:34:24 EDT 2001


"Cris A. Fugate" <fugate at lucent.com> wrote in message
news:Pine.LNX.4.33.0108101302250.611-100000 at IL0015ACSULLIV3.ih.lucent.com...
> Hi, I am trying to port some Tcl stuff to Python. Its kind of disturbing
> that Python cannot handle scope. Sure you have namespaces, but that
> doesn't help in this situation. In Tcl I would just say..
>
> proc swap {a b} {
>    upvar a x
>    upvar b y
>    set z x
>    set x y
>    set y z
> }
> swap a b
>
Not knowing Tcl, I'm assuming that "upvar" effectively means "get address
of" (a bit like the C "&" operator)?

> But in Python I have to say..
>
> def swap (a, b):
>    return b, a
> a,b = swap(a,b)
>
> -or-
>
> def swap ():
>    global a,b
>    x=a
>    a=b
>    b=x
> swap()
>
Yes, but it has a;ready been pointed out that swapping the bindings of two
names is so easy it is actually not worth defining a function for...

> I dont know if this is a good thing or a bad thing. Tcl cannot
> handle multiple assignment, but Python cannot handle scoping.
> It makes functions less powerful, but it also seems to make the
> code more readable (IMHO).
>
Python *can* handle scoping. What it can't do is change the value (outside
the function) of a name passed in. This doesn't mean Python can't change
things outside the function, they just can't be simple names.

> BTW, I also noticed that python is rather weak in variable
> substitution. In Tcl I can say..
>
> set x 5; set y "x"
> expr $$y + 1
> =>6
>
> I cant do this in python without resorting to something like
> dictionaries..
>
> y={'x':'z', 'z':5}
> y.get(y.get('x')) + 1
> =>6
>
Or possibly setattr()? By the way, you don't need to use get(), you can use
subscripting instead, so your solution would become

y[y['x']]+1
=> 6

As a matter of programming practice it is rather poor design to introduce
couplings like the ones you prefer. Effectively you make some of your
arguments "output parameters". The problem is that the values of the
variables you use as arguments are invisibly changed, with no visual clue
(like an assignment symbol) that this will happen.

There is usually an easier way to refactor your design to avoid such things,
and your program will gain in clarity by the change. If you want to do what
Tcl can do tehre wouldn't be much point doing it in Python, would there?

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list