namespace(n)
β¨ NAME β¨
namespace β bestie, it's literally the command for creating and manipulating contexts for commands and variables π
πΈ SYNOPSIS πΈ
namespace subcommand ?arg ...?
π¦ DESCRIPTION π¦
Okay so, the namespace command lets you create, access, and destroy separate contexts for commands and variables. That's it, that's the whole vibe. If you want the full lore, the section WHAT IS A NAMESPACE? down below has the overview. The legal values of subcommand are listed right here π β and yes, you can abbreviate the subcommands, she's flexible like that π
namespace children ?namespace? ?pattern?β returns a list of all the child namespaces that belong to the namespace namespace. If you don't pass a namespace, then it gives you the children of the current namespace instead. Heads up: this returns fully-qualified names, which start with a double colon (::), no exceptions. And if you give the optional pattern, it only hands back names matching that glob-style pattern. Here's the thing about the actual pattern it uses, bestie, because this part is sneaky: a pattern starting with a double colon (::) is used directly, but otherwise the namespace namespace (or the fully-qualified name of the current namespace) gets prepended onto the pattern. So like, it's building the pattern for you. Pay attention π«Άnamespace code scriptβ captures the current namespace context so script can be executed later. It returns a new script in which script has been wrapped in anamespace inscopecommand. This new script has two important properties, and they're both lowkey iconic:- It can be evaluated in any namespace and it will still cause script to be evaluated in the current namespace (aka the one where the
namespace codecommand was invoked). Time travel but make it scoped β¨ - Additional arguments can be appended to the resulting script and they'll get passed to script as additional arguments.
- It can be evaluated in any namespace and it will still cause script to be evaluated in the current namespace (aka the one where the
For example, suppose the command set script [namespace code {foo bar}] is invoked in namespace ::a::b. Then eval $script [list x y] can be executed in any namespace (assuming the value of script has been passed in properly) and will have the same effect as the command ::namespace eval ::a::b {foo bar x y}. No cap.
This command is needed because 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. The SCOPED SCRIPTS section has some examples of how this is used to create callback scripts β go look, it's giving tutorial energy π
namespace currentβ returns the fully-qualified name for the current namespace. Fun fact: 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. So it's like, lying to you a little bit, but for your own good πnamespace delete ?namespace namespace ...?β each namespace namespace is deleted, and everything inside it goes too: all variables, procedures, and child namespaces contained in the namespace. Gone. Deleted. Poof π Here's the one caveat though: 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. Also, if a namespace does not exist, this command returns an error. And if no namespace names are given, this command does nothing β it just sits there, existing, unbothered πΈnamespace ensemble subcommand ?arg ...?β creates and manipulates a command that is formed out of an ensemble of subcommands. The ENSEMBLES section below has the details, this one's a whole journey π§namespace eval namespace arg ?arg ...?β activates a namespace called namespace and evaluates some code in that context. If the namespace doesn't already exist, it gets created, no permission slip needed β¨ If more than one arg argument is specified, the arguments are concatenated together with a space between each one in the same fashion as theevalcommand, and the result is evaluated.
And if namespace has leading namespace qualifiers and any leading namespaces do not exist, they are automatically created. She's proactive like that π
namespace exists namespaceβ returns1if namespace is a valid namespace in the current context, returns0otherwise. Simple. Clean. A vibe check, basically π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 anamespace importcommand. Both commands defined in a namespace and commands the namespace has previously imported can be exported by a namespace. And the commands do not have to be defined at the time thenamespace exportcommand is executed β she's manifesting them in advance, we love to see it π¦
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 is not given, this command returns the namespace's current export list. Okay so it's a setter and a getter, she contains multitudes π
namespace forget ?pattern pattern ...?β removes previously imported commands from a namespace. Each pattern is a simple or qualified name such asx,foo::xora::b::p*. Qualified names contain double colons (::) and qualify a name with the name of one or more namespaces. Each βqualified 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 β that's the rule, don't test her π
For each βsimple patternβ this command deletes the matching commands of the current namespace that were imported from a different namespace. For βqualified patternsβ, this command first finds the matching exported commands. It then checks whether any of those commands were previously imported by the current namespace. If so, this command deletes the corresponding imported commands. In effect, this undoes the action of a namespace import command. Ctrl+Z but for namespaces, periodt β¨
namespace import ?-force? ?pattern pattern ...?β imports commands into a namespace, or queries the set of imported commands in a namespace. When no arguments are present,namespace importreturns the list of commands in the current namespace that have been imported from other namespaces. The commands in the returned list are in the format of simple names, with no namespace qualifiers at all. This format is suitable for composition withnamespace forget(see EXAMPLES below). Cute, compatible, thoughtful π
When pattern arguments are present, 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. When the namespace name is not fully qualified (i.e., does not start with a namespace separator) it is resolved as a namespace name in the way described in the NAME RESOLUTION section; it is an error if no namespace with that name can be found. No sneaky partial matches, bestie, she will simply refuse π€
All the commands that match a pattern string and which are currently 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. Silently, bestie. That's the drama flag. Use it with intention π
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 at the time when the namespace import command is executed. If another command is defined and exported in this namespace later on, it will not be imported. She took a photo of the namespace and that photo is what you get πΈ No updates, no refresh, no take-backs.
namespace inscope namespace script ?arg ...?β executes a script in the context of the specified namespace. This command is not expected to be used directly by programmers; calls to it are generated implicitly when applications usenamespace codecommands to create callback scripts that the applications then register with, e.g., Tk widgets. So it's like, backstage crew β you don't talk to it directly, it just shows up when it's needed π
The namespace inscope command is much like the namespace eval command except that the namespace must already exist, and namespace inscope appends additional args as proper list elements. Like so:
namespace inscope ::foo $script $x $y $z
is equivalent to
namespace eval ::foo [concat $script [list $x $y $z]]
thus additional arguments will not undergo a second round of substitution, as is the case with namespace eval. One pass only, she's not doing the double-dip π«Ά
namespace origin commandβ returns the fully-qualified name of the original command to which the imported command command 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 namespacesa,b,...,nwhere 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. Trace the family tree all the way back to the source, iykyk π³
And if command does not refer to an imported command, the command's own fully-qualified name is returned. No ancestry, just her own name π
namespace parent ?namespace?β returns the fully-qualified name of the parent namespace for namespace namespace. If namespace is not specified, the fully-qualified name of the current namespace's parent is returned. Parental supervision, namespace edition πnamespace path?namespaceList? β bestie, this one's the GPS of your namespace πΊοΈ It hands back the command resolution path of whatever namespace you're standing in rn. Pass it a namespaceList (a list of named namespaces) and it sets the current namespace's command resolution path to exactly those namespaces, then returns the empty list. Lowkey important: the default command resolution path is always empty, no exceptions. Peep the NAME RESOLUTION section below for how all that resolving actually works. πnamespace qualifiersstring β gives you back any leading namespace qualifiers for string. What's a qualifier? Just namespace names glued together with double colons (::). So for the string::foo::bar::x, this returns::foo::bar, and for::it returns an empty string. This is the β¨complementβ¨ ofnamespace tail, they're giving twin energy fr. And heads up: it does not check whether those namespace names are, like, actually names of currently defined namespaces. It just vibes. π¦namespace tailstring β the other half of the duo π«Ά Returns the simple name at the end of a qualified string. Qualifiers are namespace names separated by double colons (::). For::foo::bar::xyou getx, and for::you get an empty string. It's the complement ofnamespace qualifiers, periodt. Same disclaimer as its twin: it does not check whether the namespace names are in fact the names of currently defined namespaces.namespace upvarnamespace ?otherVar myVar ...? β ok so this sets up zero or more local variables in the current procedure to refer to variables over in namespace. The namespace name gets resolved per the NAME RESOLUTION section. And here's the receipts:namespace upvar $ns a bbehaves exactly the same asupvar 0 ${ns}::a bβ the sole exception being the resolution rules used for qualified namespace or variable names. It returns an empty string, iconic behaviour honestly. πnamespace unknown?script? β sets or returns the unknown command handler for the current namespace. This handler gets invoked when a command called from inside the namespace can't be found in the current namespace, nor in the namespace's path, nor in the global namespace. If you give it script, it should be a well formed list representing a command name plus optional arguments. When the handler fires, the full invocation line gets appended to the script, and the result gets evaluated in the context of the namespace. The default handler for all namespaces is::unknown. No argument? It just returns the handler for the current namespace. Easy. β¨namespace which?-command? ?-variable? name β looks up name as either a command or a variable and returns its fully-qualified name. Example time: if name doesn't exist in the current namespace but does exist in the global namespace, you get back a fully-qualified name in the global namespace. If the command or variable straight up doesn't exist, you get an empty string π. But plot twist β if the variable has been created but not defined, like with thevariablecommand or through a trace on the variable, this returns the fully-qualified name of the variable anyway. No flag given? Then name is treated as a command name. See NAME RESOLUTION below for the deets on resolving. π
π WHAT IS A NAMESPACE? π
A namespace is a collection of commands and variables, full stop. It encapsulates them so they don't interfere with the commands and variables of other namespaces. Think of it as giving your code its own little room πͺβ¨
Tcl has always had one of these collections, and we call it the global namespace. The global namespace holds all global variables and commands. And the namespace eval command is how you create new ones. For example:
namespace eval Counter {
namespace export bump
variable num 0
proc bump {} {
variable num
incr num
}
}
That creates a new namespace containing the variable num and the procedure bump. And the commands and variables in this namespace are separate from other commands and variables in the same program. So if there's a command named bump in the global namespace, bestie, it will be different from the command bump in the Counter namespace. Two different girls, same name. π
Namespace variables are giving global variables in Tcl, honestly. They exist outside of the procedures in a namespace, but you can still access them in a procedure via the variable command, exactly like in the example up there. π
Namespaces are dynamic, and this is the part that slays. 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, this series of commands has the same effect as the namespace definition shown above:
namespace eval Counter {
variable num 0
proc bump {} {
variable num
return [incr num]
}
}
namespace eval Counter {
proc test {args} {
return $args
}
}
namespace eval Counter {
rename test ""
}
Not me pointing out that the test procedure gets added to the Counter namespace, and then later removed via the rename command. Gone, but not forgotten ποΈ
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. It's giving little matryoshka dolls, iykyk πͺ
π¦ QUALIFIED NAMES π¦
Every namespace has a textual name, like history or ::safe::interp. And since namespaces can nest, we use qualified names to refer to commands, variables, and child namespaces contained inside namespaces.
Qualified names are similar to the hierarchical path names for Unix files or Tk widgets β except that :: is used as the separator instead of / or .. The topmost, aka global, namespace has the name "" (i.e., an empty string), although :: is a synonym for it. π
As an example, the name ::safe::interp::create refers to the command create in the namespace interp, which is a child of namespace ::safe, which in turn is a child of the global namespace, ::. A whole family tree fr fr π³
If you want to access commands and variables from another namespace, you must use some extra syntax. Names have to be qualified by the namespace that contains them. From the global namespace, we might access the Counter procedures like this:
Counter::bump 5
Counter::Reset
And we could access the current count like this:
puts "count = $Counter::num"
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 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, and I'm not skipping a single one π«‘ Namespaces have nonempty names except for the global namespace. :: is disallowed in simple command, variable, and namespace names except as a namespace separator. Extra colons in any separator part of a qualified name are ignored β i.e. two or more colons 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. Read that twice, bestie, it's the sneaky one π
β¨ NAME RESOLUTION β¨
okay bestie, gather: literally every Tcl command that takes variable and command names supports qualified names. Yes, all of them. So you can throw qualified names at set, proc, rename, and interp alias like itβs nothing. If you give a fully-qualified name that starts with a ::, there is no question about what command, variable, or namespace you mean. But if the name does not start with a :: (i.e., it is relative), Tcl follows basic rules for looking it up:
- Variable names are always resolved starting in the current namespace. In the absence of special resolvers,
foo::bar::bazrefers to a variable namedbazin a namespace namedbarthat is a child of a namespace namedfoothat is a child of the current namespace of the interpreter. - Command names are always resolved by looking in the current namespace first. If not found there, they are searched for in every namespace on the current namespace's command path (which is empty by default). If not found there, command names are looked up in the global namespace (or, failing that, are processed by the appropriate namespace unknown handler.)
- Namespace names are always resolved by looking in only the current namespace.
In the following example,
set traceLevel 0
namespace eval Debug {
printTrace $traceLevel
}
Tcl looks for traceLevel in the namespace Debug. It looks up the command printTrace in the same way. If a variable or command name is not found, the name is undefined. To make this point absolutely clear, consider the following example:
set traceLevel 0
namespace eval Foo {
variable traceLevel 3
namespace eval Debug {
printTrace $traceLevel
}
}
Here Tcl looks for traceLevel in the namespace Foo::Debug. The variables Foo::traceLevel and Foo::Debug::traceLevel are 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 eval Foo::Debug {namespace which -variable traceLevel}
returns the empty string. The command,
namespace eval Foo {namespace which -variable traceLevel}
returns the empty string as well.
As mentioned above, namespace names and variables are looked up differently than the names of commands. Namespace names and variables 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 ::.
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 from 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 exported 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
The namespace import command only imports commands from a namespace that that namespace exported with a namespace export command.
bestie, importing every command from a namespace is generally a bad idea since you do not 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.
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 a namespace forget command, like this:
namespace 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 eval 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 SCRIPTS π§
The namespace code command is the means by which a script may be packaged for evaluation in a namespace other than the one in which it was created. It is used most often to create event handlers, Tk bindings, and traces for evaluation in the global context. For instance, the following code indicates how to direct a variable trace callback into the current namespace:
namespace eval a {
variable b
proc theTraceCallback { n1 n2 op } {
upvar 1 $n1 var
puts "the value of $n1 has changed to $var"
return
}
trace add variable b write [namespace code theTraceCallback]
}
set a::b c
When executed, it prints the message:
the value of a::b has changed to c
π ENSEMBLES π
Okay bestie, this is the main character section. The namespace ensemble is what you use to create and manipulate ensemble commands, which are basically commands made by grouping subcommands together. It's giving "one command to rule them all". π
The commands usually come from the current namespace when the ensemble was created, though you can configure that. And note: there can be any number of ensembles tied to any namespace (including none β which is the default for literally every namespace, no cap), but here's the tea: when that namespace gets deleted, all the ensembles associated with it get deleted too. π The link between an ensemble command and its namespace is maintained however the ensemble gets renamed, though. Loyalty. π«Ά
Three subcommands of the namespace ensemble command are defined:
namespace ensemble create ?option value ...?
Creates a new ensemble command linked to the current namespace, and returns the fully qualified name of the command it created. The arguments to namespace ensemble create let you configure the command as if you'd used the namespace ensemble configure command. If you don't override it with the -command option, this command creates an ensemble with exactly the same name as the linked namespace. Peep the ENSEMBLE OPTIONS section below for the full list of supported options and what they do. β¨
namespace ensemble configure command ?option? ?value ...?
Retrieves the value of an option associated with the ensemble command named command, or updates some options associated with that ensemble command. Again, ENSEMBLE OPTIONS below has the full list. π
namespace ensemble exists command
Returns a boolean value describing whether the command command exists and is an ensemble command. This command only ever returns an error if the number of arguments is wrong. That's it, that's the whole vibe check. πΈ
When it's called, an ensemble command takes its first argument and looks it up (following the rules described below) to discover a list of words that will replace the ensemble command and subcommand. Then that resulting list of words gets evaluated (with no further substitutions) as if that's what you'd typed originally β like, by passing the list of words through Tcl_EvalObjv β and it returns the result of the command. Note that it's totally legal for the target of an ensemble rewrite to be another ensemble command, or even the same one. Recursion, we love her. π The ensemble command will not be visible through the use of the uplevel or info level commands, jsyk.
β¨ ENSEMBLE OPTIONS β¨
The following options β supported by the namespace ensemble create and namespace ensemble configure commands β control how an ensemble command behaves:
-mapβ When non-empty, this option supplies a dictionary that provides a mapping from subcommand names to a list of prefix words to substitute in place of the ensemble command and subcommand words (similar to an alias created withinterp alias; the words are not reparsed after substitution). If the first word of any target is not fully qualified when set, it's assumed to be relative to the current namespace and changed to be exactly that β meaning it's always fully qualified when read. When this option is empty, the mapping goes from the local name of the subcommand to its fully-qualified name. Note that when this option is non-empty and the-subcommandsoption is empty, the ensemble subcommand names will be exactly those words that have mappings in the dictionary. π-parametersβ This option gives a list of named arguments (the names get used during generation of error messages) that are passed by the caller of the ensemble between the name of the ensemble and the subcommand argument. By default, it's the empty list.-prefixesβ This option (enabled by default, bestie) controls whether the ensemble command recognizes unambiguous prefixes of its subcommands. When you turn it off, the ensemble command requires exact matching of subcommand names. No shortcuts. π«-subcommandsβ When non-empty, this option lists exactly what subcommands are in the ensemble. The mapping for each of those commands will be either whatever's defined in the-mapoption, or the command with the same name in the namespace linked to the ensemble. If this option is empty, the subcommands of the namespace will be either the keys of the dictionary listed in the-mapoption, or the exported commands of the linked namespace at the time the ensemble command was invoked. Timing matters, fr fr. β°-unknownβ When non-empty, this option provides a partial command (to which all the words that are arguments to the ensemble command β including the fully-qualified name of the ensemble β are appended) to handle the case where an ensemble subcommand isn't recognized and would otherwise generate an error. When empty (which is the default), an error in the style ofTcl_GetIndexFromObjis generated whenever the ensemble can't figure out how to implement a particular subcommand. See UNKNOWN HANDLER BEHAVIOUR for more deets. π
The following extra option is allowed by namespace ensemble create:
-commandβ This write-only option allows the name of the ensemble created bynamespace ensemble createto be anything in any existing namespace. The default value for this option is the fully-qualified name of the namespace in which thenamespace ensemble createcommand is invoked. π
The following extra option is allowed by namespace ensemble configure:
-namespaceβ This read-only option allows the retrieval of the fully-qualified name of the namespace which the ensemble was created within.
π΅οΈ UNKNOWN HANDLER BEHAVIOUR π΅οΈ
If an unknown handler is specified for an ensemble, that handler gets called when the ensemble command would otherwise return an error because it can't decide which subcommand to invoke. The exact conditions under which that happens are controlled by the -subcommands, -map and -prefixes options, as described above.
To execute the unknown handler, the ensemble mechanism takes the specified -unknown option and appends each argument of the attempted ensemble command invocation β including the ensemble command itself, expressed as a fully qualified name. It invokes the resulting command in the scope of the attempted call. If the execution of the unknown handler terminates normally, the ensemble engine reparses the subcommand (as described below) and tries to dispatch it again, which is ideal for when the ensemble's configuration has been updated by the unknown subcommand handler. Any other kind of termination of the unknown handler is treated as an error. π
The result of the unknown handler is expected to be a list (and it's an error if it isn't, no exceptions). If the list is an empty list, the ensemble command attempts to look up the original subcommand again, and if it's not found this time, an error gets generated just as if the -unknown handler wasn't there at all. Meaning: for any particular invocation of an ensemble, its unknown handler will be called at most once. That makes it easy for the unknown handler to update the ensemble or its backing namespace so as to provide an implementation of the desired subcommand and reparse. π
When the result is a non-empty list, the words of that list are used to replace the ensemble command and subcommand, just as if they'd been looked up in the -map. It's up to the unknown handler to supply all namespace qualifiers if the implementing subcommand isn't in the namespace of the caller of the ensemble command. Also note: when ensemble commands are chained (like if you make one of the commands that implement an ensemble subcommand into an ensemble, similar to the text widget's tag and mark subcommands), then the rewrite happens in the context of the caller of the outermost ensemble. Which is to say that ensembles do not in themselves place any namespace contexts on the Tcl call stack. π
Where an empty -unknown handler is given (the default), the ensemble command will generate an error message based on the list of commands the ensemble has defined (formatted similarly to the error message from Tcl_GetIndexFromObj). This is the error that gets thrown when the subcommand is still not recognized during reparsing. It's also an error for an -unknown handler to delete its namespace. β οΈ
Not me warning you twice β do not let your -unknown handler delete its own namespace. That's an error. Periodt.
π EXAMPLES π
Create a namespace containing a variable and an exported command:
namespace eval foo {
variable bar 0
proc grill {} {
variable bar
puts "called [incr bar] times"
}
namespace export grill
}
Call the command defined in the previous example in various ways.
# Direct call
::foo::grill
# Use the command resolution path to find the name
namespace eval boo {
namespace path ::foo
grill
}
# Import into current namespace, then call local alias
namespace import foo::grill
grill
# Create two ensembles, one with the default name and one with a
# specified name. Then call through the ensembles.
namespace eval foo {
namespace ensemble create
namespace ensemble create -command ::foobar
}
foo grill
foobar grill
Look up where the command imported in the previous example came from:
puts "grill came from [namespace origin grill]"
Remove all imported commands from the current namespace:
namespace forget {*}[namespace import]
Create an ensemble for simple working with numbers, using the -parameters option to allow the operator to be put between the first and second arguments.
namespace eval do {
namespace export *
namespace ensemble create -parameters x
proc plus {x y} {expr { $x + $y }}
proc minus {x y} {expr { $x - $y }}
}
# In use, the ensemble works like this:
puts [do 1 plus [do 9 minus 7]]
π SEE ALSO π
interp(n), upvar(n), variable(n)
π KEYWORDS π
command, ensemble, exported, internal, variable
Okay bestie, that's the whole page, you made it to the end!! π This one's from Tcl 8.5 and it's the namespace(n) page β go forth and ensemble, you absolute icon. ππ¦β¨
π¦ where this page comes from
- fedora 43: tcl-doc 1:9.0.2-1.fc43 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- fedora 44: tcl-doc 1:9.0.2-1.fc44 Β· TCL AND GPL-3.0-or-later WITH Bison-exception-2.2 AND BSD-3-Clause
- Copyright (c) 1993-1997 Bell Labs Innovations for Lucent Technologies
- Copyright (c) 1997 Sun Microsystems, Inc
- Copyright (c) 2000 Scriptics Corporation
- Copyright (c) 2004-2005 Donal K. Fellows
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms