Scope troubles with a swap function

Cris A. Fugate fugate at lucent.com
Fri Aug 10 14:42:16 EDT 2001


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)

-or-

def swap ():
   global a,b
   x=a
   a=b
   b=x
swap()

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

**********************************************************************
Cris A. Fugate          Lucent Technologies, Robust Process Automation
fugate at lucent.com       http://ihgpweb.ih.lucent.com/~fugate
630 713-8255            Sponsor of the lucent.lang.tcl newsgroup


On Fri, 10 Aug 2001, Duncan Booth wrote:

> "Matthew D. Wood" <woodm at equire.com> wrote in
> news:mailman.997452856.7709.python-list at python.org:
>
> > How do you make a swap function?
> >
> The easy way:
>
> a, b = b, a
>
> and of course you aren't restricted to two values:
>
> a, b, c = b, c, a
>
> If you are *really* sure you want a function that swaps its arguments, try:
>
> def swap(a, b): return b, a
> a, b = swap(a, b)
>
> Python isn't C. Its better.
>
> --
> Duncan Booth                                             duncan at rcp.co.uk
> int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
> "\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
>




More information about the Python-list mailing list