Search code examples
namespacestcl

Tcl: activate / deactivate namespace?


In Tcl, namespace eval <ns> <script> can be used to execute the <script> in the given namespace <ns>, e.g. namespace eval ns1 {set x 123}.

Is there a way in Tcl to activate a namespace such that the subsequent commands are executed within this namespace, and maybe later deactivate it? Fictive code:

namespace activate ns1
set x 123
namespace deactivate ns1

Solution

  • No. Commands are always executed in the current namespace.

    You could hack something together for interactive use (namespace is a built-in ensemble command so you can add to its map, and you can have your own REPL without too much work that wraps things in namespace eval at the right point) but that isn't going to be respected particularly by saved scripts.

    If you just want this to make commands (including procedures and classes) in a namespace more conveniently available, you can set a namespace path, which is a list of namespaces to resolve command names in (after the current namespace and before the global namespace; at the global level it is effectively just "after the global namespace".) It doesn't change where the things you define are made by default, and doesn't affect the lookup or either variables or namespaces. The path works by setting up a command resolver; the fixed locations of the current and global namespaces in the path resulted in the greatest compatibility with existing code in manual testing...

    For completeness... There are variable resolvers as a concept as well, but they're very hard to use (and deeply strange, and called at odd times) and really aren't recommended for anyone not diving very deep. They're not in the public language API except in one place in a very limited way that isn't helpful to your question. They mostly won't help you with where variables are created anyway.