Subject: Itcl & namespace resolution - DN [1]
David Cuthbert <dacut@kanga.org> - 24 May 2000 - comp.lang.tcl
Hi all,
One aspect of Tcl (which is seen fairly often in Itcl) that has been
annoying me lately has to do with namespace resolution. From the man page:
Tcl follows a fixed rule for looking [a non-fully-qualified name]
up: Command and variable names are always resolved by looking first
in the current namespace, and then in the global namespace.
In particular, this means that the following code is invalid:
namespace eval A {
proc B {} {}
namespace eval C { B } ;# invalid command name "B"
}
Which is expected (from the doco). OTOH, the following is valid:
namespace eval A {
proc B {} {}
proc D {} { B } ;# calls ::A::B
}
So far, so good. However, [incr Tcl] classes are treated as bona-fide
namespaces in their own right, so the following is invalid:
namespace eval A {
proc B {} {}
itcl::class C {
public method TestMethod {} { B }
}
C c
c TestMethod ;# invalid command name "B"
}
There are a few solutions to this problem, many (or possibly all) of them
not all that appealing:
1. Spell out the name of each procedure/method explicitly. While fine for
new code, this is a major pain when wrapping an existing class into a
namespace, which is how I 'stumbled' onto this problem. Formerly, all of
our classes and procedures lived in the global namespace. Moving them into
a private namespace is forcing me to revisit a few thousand lines of code.
2. Add the following after each class declaration:
namespace eval ClassName { namespace import ::Parent::* }
namespace export ClassName
And make sure that you've exported every procedure/class of interest. Still
painful, but two orders of magnitude less painful than #1. This is what I'm
currently doing to our code.
3. Rewrite Itcl so that classes are not bona-fide namespaces. This seems
silly to me; it's one of the benefits of Itcl (and, I'm guessing, the origin
of Tcl's namespaces).
4. Change the scoping rules for namespaces so that all parent namespaces
are searched in addition to (before? after?) the global namespace. For
deeply-nested namespaces, this will be a speed hit (but, IMHO, speed is less
of an issue than semantic correctness). Should parent namespaces be
searched before the global namespace? In theory, yes, but since existing
code may rely on finding something in the global namespace, this can't be
changed. Searching them after the global namespace is less logical but less
error prone.
Nonetheless, this is a change to existing well-documented behavior,
something that is never to be taken lightly.
Comments?
--
David Cuthbert
dacut@kanga.org
Last modified
2000-07-20
2000-07-20
(195.108.246.52)
Note: you are looking at
the snapshot of an old wiki
- much of this information
is likely to be very outdated
