Efficient Access to Namespace VariablesWill Duquettemiguel sofer$Revision: 1.7 $
This TIP proposes a new namespace subcommand, namespace upvar, to efficiently alias namespace variables into the current scope.
A pure-Tcl object system which defines a namespace to contain the variables for each object instance must either duplicate the object's method code in each instance namespace, or define the method code such that it exists in one namespace but accesses data from another. The Snit package [] does the latter. Instance variables are declared automatically within each method body using code like this, where "selfns" is a variable containing the name of the instance namespace:
IHVwdmFyICR7c2VsZm5zfTo6bXl2YXIgbXl2YXI=
The fully-qualified variable name "${selfns}::myvar" must be recomputed each time the method is called, which is a significant source of method-call overhead. This TIP proposes a mechanism for avoiding many of these costs while also allowing people to write clearer code.
With namespace upvar, the code would look like this:
IG5hbWVzcGFjZSB1cHZhciAkc2VsZm5zIG15dmFyIG15dmFy
The speed gains come from:
it avoids building and then destroying a Tcl_Obj for the fully qualified nameit avoids parsing the fully qualified name into its namespace/tail components, creating and then destroying the corresponding Tcl_Objsit may reuse a cached namespace in the internal representation of ${selfns}
In addition, the programmer's intention is easier to see in a command
IG5hbWVzcGFjZSB1cHZhciAkc2VsZm5zIHZhcjEgdmFyMSB2YXIyIHZhcjIgdmFyMyB2YXIz
than in the currently necessary
IHVwdmFyIDAgJHtzZWxmbnN9Ojp2YXIxIHZhcjEgJHtzZWxmbnN9Ojp2YXIyIHZhcjIgJHtzZWxmbnN9Ojp2YXIzIHZhcjM=
where the fact that all variables come from the same namespace is not so obvious.
The syntax of the new subcommand is as follows:
namespace upvar ns otherVar myVar ?otherVar myVar ...?
The semantics are identical to the following upvar call:
upvar 0 ns::otherVar myVar ?ns::otherVar myVar...?
That is, the variable otherVar in namespace ns (as resolved from the local scope) is aliased to variable myVar in the local scope.
A reference implementation of namespace upvar is being developed at SF patch #1275435 [].
This document has been placed in the public domain.