# TIP 250: Efficient Access to Namespace Variables
Author: Will Duquette <[email protected]>
Author: miguel sofer <[email protected]>
State: Final
Type: Project
Vote: Done
Created: 19-Jun-2005
Post-History:
Tcl-Version: 8.5
Tcl-Ticket: 1275435
-----
# Abstract
This TIP proposes a new **namespace** subcommand, **namespace
upvar**, to efficiently alias namespace variables into the current
scope.
# Rationale
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 <http://www.wjduquette.com/snit> 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:
upvar ${selfns}::myvar myvar
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:
namespace upvar $selfns myvar myvar
The speed gains come from:
* it avoids building and then destroying a Tcl\_Obj for the fully qualified name
* it avoids parsing the fully qualified name into its namespace/tail components, creating and then destroying the corresponding Tcl\_Objs
* it may reuse a cached namespace in the internal representation of $\{selfns\}
In addition, the programmer's intention is easier to see in a command
namespace upvar $selfns var1 var1 var2 var2 var3 var3
than in the currently necessary
upvar 0 ${selfns}::var1 var1 ${selfns}::var2 var2 ${selfns}::var3 var3
where the fact that all variables come from the same namespace is not so obvious.
# Specification
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.
# Reference Implementation
A reference implementation of **namespace upvar** is being developed at SF patch \#1275435 <https://sourceforge.net/tracker/index.php?func=detail&aid=1275435&group_id=10894&atid=310894> .
# Copyright
This document has been placed in the public domain.