where is upvar
Cary O'Brien
cobrien at Radix.Net
Fri Sep 22 09:08:56 EDT 2000
In article <39C8FEAC.1668A1C4 at sage.att.com>,
Garry Hodgson <garry at sage.att.com> wrote:
>Harald Kirsch wrote:
>>
>> Jon Ribbens <jon+python-list at unequivocal.co.uk> writes:
>> > Accessing variables in other peoples' scopes directly is nasty anyway,
>> > use function arguments ;-).
>>
>> Not if it is documented and if the sole purpose of a certain function
>> is to do that in a defined way. Those functions are sometimes called
>> `control structures'. It seems like Tcl is a bit ahead of Python here,
>> as it allows to create functions which look, smell and work like
>> custom made control structures.
>
>it's arguable whether this is a good thing or not. i've used languages
>which allowed this, including tcl. it's cute, but of limited utility.
>and the readability cost can be high.
>
One reason to have upvar in TCL is to implement call-by-reference,
rather than TCL call-by-value. Passing a variable name is
common in the builtin functions (i.e. append) and upvar lets
you implement routines that expect a variable name. I use this
a lot when there are lots of parameters to a function. Rather
than have 20 parameters, I create an array with the information
and pass the name. An upvar in the called function makes this
array available during function execution. I don't think
there is a readability cost, frankly.
Since python is, i guess, call-by-reference, you don't need this
at all.
One TCL example of a good use of "upvar" as a control structure is
something that we call sql_map, and a couple of other people have
implemented independantly. Basically it is a for loop over all the
rows in a select from a database with variable assignments. The body
runs in the context of of the caller. Oops -- This uses uplevel, not
upvar. Ok, but it is the same idea.
sql_map $sql(h) {name phone age} {
if {$age > $max_age} {
whataver...
}
}
uplevel lets you create new control structures.
You could iterate over a result set in python, but at the
cost of a throw-away function.
-- cary
More information about the Python-list
mailing list