Scope troubles with a swap function

Joseph Andrew Knapka jknapka at
Fri Aug 10 22:05:04 CEST 2001

"Cris A. Fugate" wrote:
> 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
> But in Python I have to say..
> def swap (a, b):
>    return b, a
> a,b = swap(a,b)

And the python version is quite a bit shorter
and more obvious!

> -or-
> def swap ():
>    global a,b
>    x=a
>    a=b
>    b=x
> swap()

Python has perfectly reasonable scoping (local,global,builtin).
It merely refuses to allow you access willy-nilly to arbitrary
stack frames, which is a good thing IMO. The fact that Tcl
requires such hackery in some situations is one of the things
I don't like about it (although I like Tcl a lot in general).
If you want to give a Python function access to its caller's data,
you pass references, not names.

> 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).
> 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

That's because Python objects have types, unlike Tcl
variables. In Tcl, everything is just a string, variable
and command substitution is basically a textual notion,
and the interpreter does whatever's necessary to convert
strings into whatever representation is appropriate
for the operation being performed. (Even though Tcl's now
bytecode-interpreted, the conceptual model of stringness
is still pretty much intact. Otherwise it'd be a
different language.) In Python, variables
are names of abstract objects with types and values that
can be manipulated only via the operations provided by the

Tcl and Python are really just totally different. You
shouldn't expect to be able to literally translate from
one to the other :)

# Joe Knapka
# "You know how many remote castles there are along the
#  gorges? You can't MOVE for remote castles!" - Lu Tze re. Uberwald
# 2nd Lbl A + 1 = 2nd Pause 2nd Prt A

More information about the Python-list mailing list