Tcl Built-In Commands


NAME

namespace - create and manipulate contexts for commands and variables

SYNOPSIS

namespace ?subcommand? ?arg ...?

DESCRIPTION

The namespace command lets you create, access, and destroy separate contexts for commands and variables. See the section WHAT IS A NAMESPACE? below for a brief overview of namespaces. The legal subcommand's are listed below. Note that the name of a subcommand can not be abbreviated. If the second argument in a namespace command is not identical to one of the subcommand names listed below, the command is assumed to be a namespace eval command and the second argument is assumed to be the name of a namespace.

namespace children ?name? ?pattern?
Returns a list of all child namespaces that belong to the namespace name. If name is not specified, then the children are returned for the current namespace. This command returns fully-qualified names which start with ::. If the optional pattern is given, then this command returns only the names that match the glob-style pattern. The actual pattern used is determined as follows: a pattern that starts with :: is used directly, otherwise the namespace name (or the fully-qualified name of the current namespace) is prepended onto the the pattern.

namespace code arg
Captures the current namespace context for later execution of the script arg. It returns a new Tcl scoped command that can be evaluated later to execute arg in the current namespace. It is typically used to create callback scripts, where the arg argument is a list containing a script. The command it produces is equivalent to that produced by list namespace inscope [namespace current] $arg If arg is itself a scoped command starting with namespace inscope, the result is just arg.

Extensions like Tk normally execute callback scripts in the global namespace. A scoped command captures a command together with its namespace context in a way that allows it to be executed properly later. See the section SCOPED VALUES for some examples of how this is used to create callback scripts.

namespace current
Returns the fully-qualified name for the current namespace. The actual name of the global namespace is ``'' (i.e., an empty string), but this command returns :: for the global namespace as a convenience to programmers. Tcl treats ``'' and :: as synonyms for the name of the global namespace. This make it easier to manipulate namespace names and ensures that commands like set [namespace current]::x always work.

namespace delete ?name name ...?
Each namespace name is deleted and all variables, procedures, and child namespaces contained in the namespace are deleted. name may include a sequence of namespace qualifiers separated by ::s. If a procedure is currently executing inside the namespace, the namespace will be kept alive until the procedure returns; however, the namespace is marked to prevent other code from looking it up by name. If a namespace doesn't exist, this command returns an error. If no namespace names are given, this command does nothing.

namespace ?eval? name arg ?arg ...?
Activates a namespace called name and executes some code in that context. If the namespace does not already exist, it is created. This command is normally used to define the commands and variables in a namespace. If more than one arg argument is specified, the command that is executed is the result of concatenating the arguments together with a space between each argument in the same fashion as the concat command. For convenience, the eval subcommand name argument is optional and can be omitted.

If a namespace eval command creates a new namespace name, then name determines its parent namespace and the new namespace's position in the hierarchy of namespaces. If name includes a sequence of namespace qualifiers separated by ::s, it is created as a child of the specified parent namespace; otherwise, the namespace is created as a child of the current namespace. If name has leading namespace qualifiers and any leading namespaces do not exist, they are automatically created.

namespace eval is another way (besides procedure calls) that the Tcl naming context can change. It adds a call frame to the stack to represent the namespace context. This means each namespace eval command counts as another call level for uplevel and upvar commands. For example, info level 1 will return a list describing a command that is either the outermost procedure call or the outermost namespace eval command. Also, uplevel #0 evaluates a script at top-level in the outermost namespace (the global namespace).

namespace export ?-clear? ?pattern pattern ...?
Specifies which commands are exported from a namespace. The exported commands are those that can be later imported into another namespace using a namespace import command. Both commands defined in a namespace and commands the namespace has previously imported can be exported by a namespace. The commands do not have to be defined at the time the namespace export command is executed. Each pattern may contain glob-style special characters, but it may not include any namespace qualifiers. That is, the pattern can only specify commands in the current (exporting) namespace. Each pattern is appended onto the namespace's list of export patterns. If the -clear flag is given, the namespace's export pattern list is reset to empty before any pattern arguments are appended. If no patterns are given and the -clear flag isn't given, this command returns the namespace's current export list.

namespace forget ?pattern pattern ...?
Removes previously imported commands from a namespace. Each pattern is a qualified name like foo::x or a::b::p*. Qualified names contain ::s and qualify a name with the name of one or more namespaces. Each pattern is qualified with the name of an exporting namespace and may have glob-style special characters in the command name at the end of the qualified name. Glob characters may not appear in a namespace name. This command first finds the matching exported commands. It then checks whether any of those those commands were previously imported by the current namespace. If so, this command deletes the corresponding imported command. In effect, this un-does the action of a namespace import command.

namespace import ?-force? ?pattern pattern ...?
Imports commands into a namespace. Each pattern is a qualified name like foo::x or a::p*. That is, it includes the name of an exporting namespace and may have glob-style special characters in the command name at the end of the qualified name. Glob characters may not appear in a namespace name. All the commands that match a pattern string and which are exported from their namespace are added to the current namespace. This is done by creating a new command in the current namespace that points to the exported command in its original namespace; when the new imported command is called, it invokes the exported command. This command normally returns an error if an imported command conflicts with an existing command. However, if the -force option is given, imported commands will silently replace existing commands.

namespace inscope name arg ?arg ...?
Executes a script in the context of a particular namespace. This command is not expected to be used directly by programmers; calls to it are generated implicitly when applications use namespace code commands to create callback scripts that the applications then register with, e.g., Tk widgets. The namespace inscope command is much like the namespace eval command except that it has lappend semantics and the namespace must already exist. It treats the first argument as a list, and appends any arguments after the first onto the end as proper list elements. namespace inscope ::foo a x y z is equivalent to namespace eval ::foo [concat a [list x y z]] This lappend semantics is important because many callback scripts are actually prefixes.

namespace origin name
Returns the fully-qualified name of the original command to which the imported command name refers. When a command is imported into a namespace, a new command is created in that namespace that points to the actual command in the exporting namespace. If a command is imported into a sequence of namespaces a, b,...,n where each successive namespace just imports the command from the previous namespace, this command returns the fully-qualified name of the original command in the first namespace, a. If name does not refer to an imported command, the command's own fully-qualified name is returned.

namespace parent ?name?
Returns the fully-qualified name of the parent namespace for namespace name. If name is not specified, the fully-qualified name of the current namespace's parent is returned.

namespace qualifiers string
Returns any leading namespace qualifiers for string. Qualifiers are namespace names separated by ::s. For the string ::foo::bar::x, this command returns ::foo::bar, and for :: it returns ``'' (an empty string). This command is the complement of the namespace tail command. Note that it does not check whether the namespace names are, in fact, the names of currently defined namespaces.

namespace tail string
Returns the simple name at the end of a qualified string. Qualifiers are namespace names separated by ::s. For the string ::foo::bar::x, this command returns x, and for :: it returns ``'' (an empty string). This command is the complement of the namespace qualifiers command. It does not check whether the namespace names are, in fact, the names of currently defined namespaces.

namespace which ?-command? ?-variable? name
Looks up name as either a command or variable and returns its fully-qualified name. For example, if name does not exist in the current namespace but does exist in the global namespace, this command returns a fully-qualified name in the global namespace. If the command or variable does not exist, this command returns an empty string. If no flag is given, name is treated as a command name. See the section NAME RESOLUTION below for an explanation of the rules regarding name resolution.

WHAT IS A NAMESPACE?

A namespace is a collection of commands and variables. It encapsulates the commands and variables to ensure that they won't interfere with the commands and variables of other namespaces. Tcl has always had one such collection, which we refer to as the global namespace. The global namespace holds all global variables and commands. The namespace eval command lets you create new namespaces. For example,
namespace eval Counter {
    namespace export Bump
    variable num 0
    proc Bump {} {
        variable num
        incr num
    }
}
creates a new namespace containing the variable num and the procedure Bump. The commands and variables in this namespace are separate from other commands and variables in the same program. If there is a command named Bump in the global namespace, for example, it will not interfere with the command Bump in the Counter namespace.

Namespace variables resemble global variables in Tcl. They exist outside of the procedures in a namespace but can be accessed in a procedure via the variable command, as shown in the example above.

Namespaces are dynamic. You can add and delete commands and variables at any time. So you can build up the contents of a namespace over time using a series of namespace eval commands. For example, the following series of commands has the same effect as the namespace definition shown above:

namespace Counter {
    variable num 0
    proc Bump {} {
        variable num
        return [incr num]
    }
}
namespace Counter {
    proc test {args} {
        return $args
    }
}
namespace Counter {
    rename test ""
}
Note that the test procedure is added to the Counter namespace, and later removed via the rename command.

Namespaces can have other namespaces within them, so they nest hierarchically. A nested namespace is encapsulated inside its parent namespace and can not interfere with other namespaces. If namespaces are used to represent packages, this feature lets one package contain its own copy of another package.

QUALIFIED NAMES

Procedures execute in the context of the namespace that contains them. So in the following namespace,
namespace Counter {
    namespace export Bump Reset
    variable num 0
    proc Bump {{by 1}} {
        variable num
        return [incr num $by]
    }
    proc Reset {} {
        variable num
        set num 0
    }
}
procedures like Bump and Reset execute in the context of namespace Counter.

In this context, you can access the commands and variables that reside in the namespace using simple names. In the example above, we access the num variable with the command variable num. (We can't use global num since that would only look up num in the global namespace.) We can access the Bump and Reset procedures in another procedure like this:

namespace Counter {
    namespace export Rebump
    proc Rebump {{by 1}} {
        Reset
        Bump $by
    }
}
This is the real benefit of namespaces. The commands and variables in a namespace fit together as a module.

If you want to access commands and variables from another namespace, you must use some extra syntax. Names must be qualified by the namespace that contains them. The :: string acts as a separator between the various qualifiers in a name. From the global namespace, we might access the Counter procedures like this:

Counter::Bump 5
Counter::Reset
Counter::Rebump 10
We could access the current count like this:
puts "count = $Counter::num"
set Counter::num 35
When one namespace contains another, you may need more than one qualifier to reach its elements. If we had a namespace Foo that contained the namespace Counter, you could invoke its Bump procedure from the global namespace like this:
Foo::Counter::Bump 3
You can think of namespaces like directories in a file system. When you are sitting in a particular directory context, you can access files with simple names. But from another context, you must use a proper path name. A name like Foo::Counter::Bump is just like a file name Foo/Counter/Bump, except that we have used :: instead of / as the separator. Just as the file system has a root directory /, all namespaces are rooted in the global namespace named ::. So all names can be given with an absolute path that begins with ::. For example, we can say:
::Foo::Counter::Bump 3
With this name, you can be sure that you'll get the Bump procedure in the Counter namespace, in the Foo namespace, in the global namespace-no matter what the current namespace context may be.

You can also use qualified names when you create and rename commands. For example, you could add a procedure to the Foo namespace like this:

proc Foo::Test {args} {return $args}
And you could move the same procedure to another namespace like this:
rename Foo::Test Bar::Test

There are a few remaining points about qualified names that we should cover. :: is disallowed in both simple command and variable names except as a namespace separator. Extra :s in a qualified name are ignored; that is, two or more :s are treated as a namespace separator. A trailing :: in a qualified variable or command name refers to the variable or command named {}. However, a trailing :: in a qualified namespace name is ignored.

NAME RESOLUTION

In general, all Tcl commands that take variable and command names support qualified names. This means you can give qualified names to such commands as set, proc, rename, and interp alias. If you provide a fully-qualified name that starts with a ::, there is no question about what command, variable, or namespace you mean. However, if the name does not start with a :: (i.e., is relative), Tcl follows a fixed rule for looking it up: Command and variable names are always resolved by looking first in the current namespace, and then in the global namespace. Namespace namess, on the other hand, are always resolved by looking in only the current namespace.

In the following example,

set traceLevel 0
namespace Debug {
    printTrace $traceLevel
}
Tcl looks for traceLevel in the namespace Debug and then in the global namespace. It looks up the command printTrace in the same way. If a variable or command name is not found in either context, the name is undefined. To make this point absolutely clear, consider the following example:
set traceLevel 0
namespace Foo {
    variable traceLevel 3
    namespace Debug {
        printTrace $traceLevel
    }
}
Here Tcl looks for traceLevel first in the namespace Foo::Debug. Since it is not found there, Tcl then looks for it in the global namespace. The variable Foo::traceLevel is completely ignored during the name resolution process.

You can use the namespace which command to clear up any question about name resolution. For example, the command:

namespace Foo::Debug {namespace which -variable traceLevel}
returns ::traceLevel. On the other hand, the command,
namespace Foo {namespace which -variable traceLevel}
returns ::Foo::traceLevel.

Although Tcl always follows the ``look in the current then in the global namespace'' rule for variables and commands, there is a question of how to resolve a qualified name like foo::bar::cmd. A relative name like this might resolve to either [namespace current]::foo::bar::cmd or to ::foo::bar::cmd. If cmd does not appear in [namespace current]::foo::bar but does appear in ::foo::bar, Tcl assumes it refers to the latter command.

As mentioned above, namespace names are looked up differently than the names of variables and commands. Namespace names are always resolved in the current namespace. This means, for example, that a namespace eval command that creates a new namespace always creates a child of the current namespace unless the new namespace name begins with a ::.

Tcl has no access control to limit what variables, commands, or namespaces you can reference. If you provide a qualified name that resolves to an element by the name resolution rule above, you can access the element.

You can access a namespace variable within a procedure in the same namespace by using the variable command. Much like the global command, this creates a local link to the namespace variable. If necessary, it also creates the variable in the current namespace and initializes it. Note that the global command only creates links to variables in the global namespace. It is not necessary to use a variable command if you always refer to the namespace variable using an appropriate qualified name.

IMPORTING COMMANDS

Namespaces are often used to represent libraries. Some library commands are used so frequently that it is a nuisance to type their qualified names. For example, suppose that all of the commands in a package like BLT are contained in a namespace called Blt. Then you might access these commands like this:
Blt::graph .g -background red
Blt::table . .g 0,0
If you use the graph and table commands frequently, you may want to access them without the Blt:: prefix. You can do this by importing the commands into the current namespace, like this:
namespace import Blt::*
This adds all commands from the Blt namespace into the current namespace context, so you can write code like this:
graph .g -background red
table . .g 0,0
Importing every command from a namespace is generally a bad idea since you don't know what you will get. It is better to import just the specific commands you need. For example, the command
namespace import Blt::graph Blt::table
imports only the graph and table commands into the current context.

The namespace import command has snapshot semantics: that is, only requested commands that are currently defined in the exporting namespace are imported. In other words, you can import only the commands that are in a namespace like Blt at the time when the namespace import command is executed. If another command appears in this namespace later on, it will not be imported.

If you try to import a command that already exists, you will get an error. This prevents you from importing the same command from two different packages. But from time to time (perhaps when debugging), you may want to get around this restriction. You may want to reissue the namespace import command to pick up new commands that have appeared in a namespace. In that case, you can use the -force option, and existing commands will be silently overwritten:

namespace import -force Blt::graph Blt::table
If for some reason, you want to stop using the imported commands, you can remove them with an import forget command, like this:
import forget Blt::*
This searches the current namespace for any commands imported from Blt. If it finds any, it removes them. Otherwise, it does nothing. After this, the Blt commands must be accessed with the Blt:: prefix.

When you delete a command from the exporting namespace like this:

rename Blt::graph ""
the command is automatically removed from all namespaces that import it.

EXPORTING COMMANDS

You can export commands from a namespace like this:
namespace Counter {
    namespace export Bump Reset
    variable num 0
    variable max 100
    proc Bump {{by 1}} {
        variable num
        incr num $by
        check
        return $num
    }
    proc Reset {} {
        variable num
        set num 0
    }
    proc check {} {
        variable num
        variable max
        if {$num > $max} {
            error "too high!"
        }
    }
}
The procedures Bump and Reset are exported, so they are included when you import from the Counter namespace, like this:
namespace import Counter::*
However, the check procedure is not exported, so it is ignored by the import operation.

The namespace import command only imports commands that were declared as exported by their namespace. The namespace export command specifies what commands may be imported by other namespaces. If a namespace import command specifies a command that is not exported, the command is not imported.

SCOPED VALUES

Extensions like Tk execute ordinary code fragments in the global namespace. A scoped command captures a script together with its namespace in a way that allows it to be executed properly later. It is needed, for example, to wrap up script when a Tk widget is used within a namespace. It is also needed for commands such as after that execute a script at the global level at some future time. If a after command is executed in a namespace, a namespace code command is needed to ensure its script executes in the correct context:
namespace Foo {
    variable v 123
    proc report {msg} {
        puts "$msg"
    }
    after 2000 [namespace code {report "Hello World, v = $v"}]
}

SEE ALSO

variable(n)

KEYWORDS

exported, internal, variable

Last change: 8.0

[ tcl8.0b1 | tk8.0b1 | X-ref ]

Copyright © 1989-1994 The Regents of the University of California.
Copyright © 1994-1997 Sun Microsystems, Inc.