Scope troubles with a swap function

Steven D. Majewski sdm7g at Virginia.EDU
Fri Aug 10 17:23:20 EDT 2001


On Fri, 10 Aug 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)

I can't write Lisp expressions of FORTH in Python either, but that
limitation hardly interferes with what I can do with Python. 

Is there something you can't do in Python or is it just that you
don't like (or aren't used to) the Python way of doing it. 

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

I would say that Python has different scoping rules than Tcl --
not that it can't handle scoping. 

> 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

y[y['x']] + 1  

might be slightly more clear, but even better would be to use a 
variable for the indirect indexing:

x='z'
y[x]+1


The most literal translation of your Tcl into Python would be:

>>> x=5
>>> y='x'
>>> eval(y) + 1
6

( 'eval' does the same sort of indirection as Tcl's 'expr' )

but you won't often see that sort of expression in Python code,
since there are better ways to do it.

I find multiple levels of string substitution to easily get confusing.
Tcl uses substitution for a lot of things just because it doesn't have
a large set of rich data structures.  Python's dictionaries, classes
and modules give you a richer vocabulary. 

You can write a Python equivalent of 'upvar' also, but it would look
ugly in Python.


-- Steve Majewski






More information about the Python-list mailing list