1namespace(n) Tcl Built-In Commands namespace(n)
2
3
4
5______________________________________________________________________________
6
8 namespace - create and manipulate contexts for commands and variables
9
11 namespace ?subcommand? ?arg ...?
12______________________________________________________________________________
13
15 The namespace command lets you create, access, and destroy separate
16 contexts for commands and variables. See the section WHAT IS A NAME‐
17 SPACE? below for a brief overview of namespaces. The legal values of
18 subcommand are listed below. Note that you can abbreviate the subcom‐
19 mands.
20
21 namespace children ?namespace? ?pattern?
22 Returns a list of all child namespaces that belong to the name‐
23 space namespace. If namespace is not specified, then the chil‐
24 dren are returned for the current namespace. This command re‐
25 turns fully-qualified names, which start with a double colon
26 (::). If the optional pattern is given, then this command re‐
27 turns only the names that match the glob-style pattern. The ac‐
28 tual pattern used is determined as follows: a pattern that
29 starts with double colon (::) is used directly, otherwise the
30 namespace namespace (or the fully-qualified name of the current
31 namespace) is prepended onto the pattern.
32
33 namespace code script
34 Captures the current namespace context for later execution of
35 the script script. It returns a new script in which script has
36 been wrapped in a namespace inscope command. The new script has
37 two important properties. First, it can be evaluated in any
38 namespace and will cause script to be evaluated in the current
39 namespace (the one where the namespace code command was in‐
40 voked). Second, additional arguments can be appended to the re‐
41 sulting script and they will be passed to script as additional
42 arguments. For example, suppose the command set script [name‐
43 space code {foo bar}] is invoked in namespace ::a::b. Then eval
44 $script [list x y] can be executed in any namespace (assuming
45 the value of script has been passed in properly) and will have
46 the same effect as the command ::namespace eval ::a::b {foo bar
47 x y}. This command is needed because extensions like Tk nor‐
48 mally execute callback scripts in the global namespace. A
49 scoped command captures a command together with its namespace
50 context in a way that allows it to be executed properly later.
51 See the section SCOPED SCRIPTS for some examples of how this is
52 used to create callback scripts.
53
54 namespace current
55 Returns the fully-qualified name for the current namespace. The
56 actual name of the global namespace is “” (i.e., an empty
57 string), but this command returns :: for the global namespace as
58 a convenience to programmers.
59
60 namespace delete ?namespace namespace ...?
61 Each namespace namespace is deleted and all variables, proce‐
62 dures, and child namespaces contained in the namespace are
63 deleted. If a procedure is currently executing inside the name‐
64 space, the namespace will be kept alive until the procedure re‐
65 turns; however, the namespace is marked to prevent other code
66 from looking it up by name. If a namespace does not exist, this
67 command returns an error. If no namespace names are given, this
68 command does nothing.
69
70 namespace ensemble subcommand ?arg ...?
71 Creates and manipulates a command that is formed out of an en‐
72 semble of subcommands. See the section ENSEMBLES below for fur‐
73 ther details.
74
75 namespace eval namespace arg ?arg ...?
76 Activates a namespace called namespace and evaluates some code
77 in that context. If the namespace does not already exist, it is
78 created. If more than one arg argument is specified, the argu‐
79 ments are concatenated together with a space between each one in
80 the same fashion as the eval command, and the result is evalu‐
81 ated.
82
83 If namespace has leading namespace qualifiers and any leading
84 namespaces do not exist, they are automatically created.
85
86 namespace exists namespace
87 Returns 1 if namespace is a valid namespace in the current con‐
88 text, returns 0 otherwise.
89
90 namespace export ?-clear? ?pattern pattern ...?
91 Specifies which commands are exported from a namespace. The ex‐
92 ported commands are those that can be later imported into an‐
93 other namespace using a namespace import command. Both commands
94 defined in a namespace and commands the namespace has previously
95 imported can be exported by a namespace. The commands do not
96 have to be defined at the time the namespace export command is
97 executed. Each pattern may contain glob-style special charac‐
98 ters, but it may not include any namespace qualifiers. That is,
99 the pattern can only specify commands in the current (exporting)
100 namespace. Each pattern is appended onto the namespace's list
101 of export patterns. If the -clear flag is given, the name‐
102 space's export pattern list is reset to empty before any pattern
103 arguments are appended. If no patterns are given and the -clear
104 flag is not given, this command returns the namespace's current
105 export list.
106
107 namespace forget ?pattern pattern ...?
108 Removes previously imported commands from a namespace. Each
109 pattern is a simple or qualified name such as x, foo::x or
110 a::b::p*. Qualified names contain double colons (::) and qual‐
111 ify a name with the name of one or more namespaces. Each “qual‐
112 ified pattern” is qualified with the name of an exporting name‐
113 space and may have glob-style special characters in the command
114 name at the end of the qualified name. Glob characters may not
115 appear in a namespace name. For each “simple pattern” this com‐
116 mand deletes the matching commands of the current namespace that
117 were imported from a different namespace. For “qualified pat‐
118 terns”, this command first finds the matching exported commands.
119 It then checks whether any of those commands were previously im‐
120 ported by the current namespace. If so, this command deletes
121 the corresponding imported commands. In effect, this un-does
122 the action of a namespace import command.
123
124 namespace import ?-force? ?pattern pattern ...?
125 Imports commands into a namespace, or queries the set of im‐
126 ported commands in a namespace. When no arguments are present,
127 namespace import returns the list of commands in the current
128 namespace that have been imported from other namespaces. The
129 commands in the returned list are in the format of simple names,
130 with no namespace qualifiers at all. This format is suitable
131 for composition with namespace forget (see EXAMPLES below).
132
133 When pattern arguments are present, each pattern is a qualified
134 name like foo::x or a::p*. That is, it includes the name of an
135 exporting namespace and may have glob-style special characters
136 in the command name at the end of the qualified name. Glob
137 characters may not appear in a namespace name. When the name‐
138 space name is not fully qualified (i.e., does not start with a
139 namespace separator) it is resolved as a namespace name in the
140 way described in the NAME RESOLUTION section; it is an error if
141 no namespace with that name can be found.
142
143 All the commands that match a pattern string and which are cur‐
144 rently exported from their namespace are added to the current
145 namespace. This is done by creating a new command in the cur‐
146 rent namespace that points to the exported command in its origi‐
147 nal namespace; when the new imported command is called, it in‐
148 vokes the exported command. This command normally returns an
149 error if an imported command conflicts with an existing command.
150 However, if the -force option is given, imported commands will
151 silently replace existing commands. The namespace import com‐
152 mand has snapshot semantics: that is, only requested commands
153 that are currently defined in the exporting namespace are im‐
154 ported. In other words, you can import only the commands that
155 are in a namespace at the time when the namespace import command
156 is executed. If another command is defined and exported in this
157 namespace later on, it will not be imported.
158
159 namespace inscope namespace script ?arg ...?
160 Executes a script in the context of the specified namespace.
161 This command is not expected to be used directly by programmers;
162 calls to it are generated implicitly when applications use name‐
163 space code commands to create callback scripts that the applica‐
164 tions then register with, e.g., Tk widgets. The namespace in‐
165 scope command is much like the namespace eval command except
166 that the namespace must already exist, and namespace inscope ap‐
167 pends additional args as proper list elements.
168
169 namespace inscope ::foo $script $x $y $z
170
171 is equivalent to
172
173 namespace eval ::foo [concat $script [list $x $y $z]]
174
175 thus additional arguments will not undergo a second round of
176 substitution, as is the case with namespace eval.
177
178 namespace origin command
179 Returns the fully-qualified name of the original command to
180 which the imported command command refers. When a command is
181 imported into a namespace, a new command is created in that
182 namespace that points to the actual command in the exporting
183 namespace. If a command is imported into a sequence of name‐
184 spaces a, b,...,n where each successive namespace just imports
185 the command from the previous namespace, this command returns
186 the fully-qualified name of the original command in the first
187 namespace, a. If command does not refer to an imported command,
188 the command's own fully-qualified name is returned.
189
190 namespace parent ?namespace?
191 Returns the fully-qualified name of the parent namespace for
192 namespace namespace. If namespace is not specified, the fully-
193 qualified name of the current namespace's parent is returned.
194
195 namespace path ?namespaceList?
196 Returns the command resolution path of the current namespace. If
197 namespaceList is specified as a list of named namespaces, the
198 current namespace's command resolution path is set to those
199 namespaces and returns the empty list. The default command reso‐
200 lution path is always empty. See the section NAME RESOLUTION be‐
201 low for an explanation of the rules regarding name resolution.
202
203 namespace qualifiers string
204 Returns any leading namespace qualifiers for string. Qualifiers
205 are namespace names separated by double colons (::). For the
206 string ::foo::bar::x, this command returns ::foo::bar, and for
207 :: it returns an empty string. This command is the complement
208 of the namespace tail command. Note that it does not check
209 whether the namespace names are, in fact, the names of currently
210 defined namespaces.
211
212 namespace tail string
213 Returns the simple name at the end of a qualified string. Qual‐
214 ifiers are namespace names separated by double colons (::). For
215 the string ::foo::bar::x, this command returns x, and for :: it
216 returns an empty string. This command is the complement of the
217 namespace qualifiers command. It does not check whether the
218 namespace names are, in fact, the names of currently defined
219 namespaces.
220
221 namespace upvar namespace ?otherVar myVar ...?
222 This command arranges for zero or more local variables in the
223 current procedure to refer to variables in namespace. The name‐
224 space name is resolved as described in section NAME RESOLUTION.
225 The command namespace upvar $ns a b has the same behaviour as
226 upvar 0 ${ns}::a b, with the sole exception of the resolution
227 rules used for qualified namespace or variable names. namespace
228 upvar returns an empty string.
229
230 namespace unknown ?script?
231 Sets or returns the unknown command handler for the current
232 namespace. The handler is invoked when a command called from
233 within the namespace cannot be found in the current namespace,
234 the namespace's path nor in the global namespace. The script
235 argument, if given, should be a well formed list representing a
236 command name and optional arguments. When the handler is in‐
237 voked, the full invocation line will be appended to the script
238 and the result evaluated in the context of the namespace. The
239 default handler for all namespaces is ::unknown. If no argument
240 is given, it returns the handler for the current namespace.
241
242 namespace which ?-command? ?-variable? name
243 Looks up name as either a command or variable and returns its
244 fully-qualified name. For example, if name does not exist in
245 the current namespace but does exist in the global namespace,
246 this command returns a fully-qualified name in the global name‐
247 space. If the command or variable does not exist, this command
248 returns an empty string. If the variable has been created but
249 not defined, such as with the variable command or through a
250 trace on the variable, this command will return the fully-quali‐
251 fied name of the variable. If no flag is given, name is treated
252 as a command name. See the section NAME RESOLUTION below for an
253 explanation of the rules regarding name resolution.
254
256 A namespace is a collection of commands and variables. It encapsulates
257 the commands and variables to ensure that they will not interfere with
258 the commands and variables of other namespaces. Tcl has always had one
259 such collection, which we refer to as the global namespace. The global
260 namespace holds all global variables and commands. The namespace eval
261 command lets you create new namespaces. For example,
262
263 namespace eval Counter {
264 namespace export bump
265 variable num 0
266
267 proc bump {} {
268 variable num
269 incr num
270 }
271 }
272
273 creates a new namespace containing the variable num and the procedure
274 bump. The commands and variables in this namespace are separate from
275 other commands and variables in the same program. If there is a com‐
276 mand named bump in the global namespace, for example, it will be dif‐
277 ferent from the command bump in the Counter namespace.
278
279 Namespace variables resemble global variables in Tcl. They exist out‐
280 side of the procedures in a namespace but can be accessed in a proce‐
281 dure via the variable command, as shown in the example above.
282
283 Namespaces are dynamic. You can add and delete commands and variables
284 at any time, so you can build up the contents of a namespace over time
285 using a series of namespace eval commands. For example, the following
286 series of commands has the same effect as the namespace definition
287 shown above:
288
289 namespace eval Counter {
290 variable num 0
291 proc bump {} {
292 variable num
293 return [incr num]
294 }
295 }
296 namespace eval Counter {
297 proc test {args} {
298 return $args
299 }
300 }
301 namespace eval Counter {
302 rename test ""
303 }
304
305 Note that the test procedure is added to the Counter namespace, and
306 later removed via the rename command.
307
308 Namespaces can have other namespaces within them, so they nest hierar‐
309 chically. A nested namespace is encapsulated inside its parent name‐
310 space and can not interfere with other namespaces.
311
313 Each namespace has a textual name such as history or ::safe::interp.
314 Since namespaces may nest, qualified names are used to refer to com‐
315 mands, variables, and child namespaces contained inside namespaces.
316 Qualified names are similar to the hierarchical path names for Unix
317 files or Tk widgets, except that :: is used as the separator instead of
318 / or .. The topmost or global namespace has the name “” (i.e., an
319 empty string), although :: is a synonym. As an example, the name
320 ::safe::interp::create refers to the command create in the namespace
321 interp that is a child of namespace ::safe, which in turn is a child of
322 the global namespace, ::.
323
324 If you want to access commands and variables from another namespace,
325 you must use some extra syntax. Names must be qualified by the name‐
326 space that contains them. From the global namespace, we might access
327 the Counter procedures like this:
328
329 Counter::bump 5
330 Counter::Reset
331
332 We could access the current count like this:
333
334 puts "count = $Counter::num"
335
336 When one namespace contains another, you may need more than one quali‐
337 fier to reach its elements. If we had a namespace Foo that contained
338 the namespace Counter, you could invoke its bump procedure from the
339 global namespace like this:
340
341 Foo::Counter::bump 3
342
343 You can also use qualified names when you create and rename commands.
344 For example, you could add a procedure to the Foo namespace like this:
345
346 proc Foo::Test {args} {return $args}
347
348 And you could move the same procedure to another namespace like this:
349
350 rename Foo::Test Bar::Test
351
352 There are a few remaining points about qualified names that we should
353 cover. Namespaces have nonempty names except for the global namespace.
354 :: is disallowed in simple command, variable, and namespace names ex‐
355 cept as a namespace separator. Extra colons in any separator part of a
356 qualified name are ignored; i.e. two or more colons are treated as a
357 namespace separator. A trailing :: in a qualified variable or command
358 name refers to the variable or command named {}. However, a trailing
359 :: in a qualified namespace name is ignored.
360
362 In general, all Tcl commands that take variable and command names sup‐
363 port qualified names. This means you can give qualified names to such
364 commands as set, proc, rename, and interp alias. If you provide a
365 fully-qualified name that starts with a ::, there is no question about
366 what command, variable, or namespace you mean. However, if the name
367 does not start with a :: (i.e., is relative), Tcl follows basic rules
368 for looking it up:
369
370 • Variable names are always resolved by looking first in the cur‐
371 rent namespace, and then in the global namespace.
372
373 • Command names are always resolved by looking in the current
374 namespace first. If not found there, they are searched for in
375 every namespace on the current namespace's command path (which
376 is empty by default). If not found there, command names are
377 looked up in the global namespace (or, failing that, are pro‐
378 cessed by the appropriate namespace unknown handler.)
379
380 • Namespace names are always resolved by looking in only the cur‐
381 rent namespace.
382
383 In the following example,
384
385 set traceLevel 0
386 namespace eval Debug {
387 printTrace $traceLevel
388 }
389
390 Tcl looks for traceLevel in the namespace Debug and then in the global
391 namespace. It looks up the command printTrace in the same way. If a
392 variable or command name is not found in either context, the name is
393 undefined. To make this point absolutely clear, consider the following
394 example:
395
396 set traceLevel 0
397 namespace eval Foo {
398 variable traceLevel 3
399
400 namespace eval Debug {
401 printTrace $traceLevel
402 }
403 }
404
405 Here Tcl looks for traceLevel first in the namespace Foo::Debug. Since
406 it is not found there, Tcl then looks for it in the global namespace.
407 The variable Foo::traceLevel is completely ignored during the name res‐
408 olution process.
409
410 You can use the namespace which command to clear up any question about
411 name resolution. For example, the command:
412
413 namespace eval Foo::Debug {namespace which -variable traceLevel}
414
415 returns ::traceLevel. On the other hand, the command,
416
417 namespace eval Foo {namespace which -variable traceLevel}
418
419 returns ::Foo::traceLevel.
420
421 As mentioned above, namespace names are looked up differently than the
422 names of variables and commands. Namespace names are always resolved
423 in the current namespace. This means, for example, that a namespace
424 eval command that creates a new namespace always creates a child of the
425 current namespace unless the new namespace name begins with ::.
426
427 Tcl has no access control to limit what variables, commands, or name‐
428 spaces you can reference. If you provide a qualified name that re‐
429 solves to an element by the name resolution rule above, you can access
430 the element.
431
432 You can access a namespace variable from a procedure in the same name‐
433 space by using the variable command. Much like the global command,
434 this creates a local link to the namespace variable. If necessary, it
435 also creates the variable in the current namespace and initializes it.
436 Note that the global command only creates links to variables in the
437 global namespace. It is not necessary to use a variable command if you
438 always refer to the namespace variable using an appropriate qualified
439 name.
440
442 Namespaces are often used to represent libraries. Some library com‐
443 mands are used so frequently that it is a nuisance to type their quali‐
444 fied names. For example, suppose that all of the commands in a package
445 like BLT are contained in a namespace called Blt. Then you might ac‐
446 cess these commands like this:
447
448 Blt::graph .g -background red
449 Blt::table . .g 0,0
450
451 If you use the graph and table commands frequently, you may want to ac‐
452 cess them without the Blt:: prefix. You can do this by importing the
453 commands into the current namespace, like this:
454
455 namespace import Blt::*
456
457 This adds all exported commands from the Blt namespace into the current
458 namespace context, so you can write code like this:
459
460 graph .g -background red
461 table . .g 0,0
462
463 The namespace import command only imports commands from a namespace
464 that that namespace exported with a namespace export command.
465
466 Importing every command from a namespace is generally a bad idea since
467 you do not know what you will get. It is better to import just the
468 specific commands you need. For example, the command
469
470 namespace import Blt::graph Blt::table
471
472 imports only the graph and table commands into the current context.
473
474 If you try to import a command that already exists, you will get an er‐
475 ror. This prevents you from importing the same command from two dif‐
476 ferent packages. But from time to time (perhaps when debugging), you
477 may want to get around this restriction. You may want to reissue the
478 namespace import command to pick up new commands that have appeared in
479 a namespace. In that case, you can use the -force option, and existing
480 commands will be silently overwritten:
481
482 namespace import -force Blt::graph Blt::table
483
484 If for some reason, you want to stop using the imported commands, you
485 can remove them with a namespace forget command, like this:
486
487 namespace forget Blt::*
488
489 This searches the current namespace for any commands imported from Blt.
490 If it finds any, it removes them. Otherwise, it does nothing. After
491 this, the Blt commands must be accessed with the Blt:: prefix.
492
493 When you delete a command from the exporting namespace like this:
494
495 rename Blt::graph ""
496
497 the command is automatically removed from all namespaces that import
498 it.
499
501 You can export commands from a namespace like this:
502
503 namespace eval Counter {
504 namespace export bump reset
505 variable Num 0
506 variable Max 100
507
508 proc bump {{by 1}} {
509 variable Num
510 incr Num $by
511 Check
512 return $Num
513 }
514 proc reset {} {
515 variable Num
516 set Num 0
517 }
518 proc Check {} {
519 variable Num
520 variable Max
521 if {$Num > $Max} {
522 error "too high!"
523 }
524 }
525 }
526
527 The procedures bump and reset are exported, so they are included when
528 you import from the Counter namespace, like this:
529
530 namespace import Counter::*
531
532 However, the Check procedure is not exported, so it is ignored by the
533 import operation.
534
535 The namespace import command only imports commands that were declared
536 as exported by their namespace. The namespace export command specifies
537 what commands may be imported by other namespaces. If a namespace im‐
538 port command specifies a command that is not exported, the command is
539 not imported.
540
542 The namespace code command is the means by which a script may be pack‐
543 aged for evaluation in a namespace other than the one in which it was
544 created. It is used most often to create event handlers, Tk bindings,
545 and traces for evaluation in the global context. For instance, the
546 following code indicates how to direct a variable trace callback into
547 the current namespace:
548
549 namespace eval a {
550 variable b
551 proc theTraceCallback { n1 n2 op } {
552 upvar 1 $n1 var
553 puts "the value of $n1 has changed to $var"
554 return
555 }
556 trace add variable b write [namespace code theTraceCallback]
557 }
558 set a::b c
559
560 When executed, it prints the message:
561
562 the value of a::b has changed to c
563
565 The namespace ensemble is used to create and manipulate ensemble com‐
566 mands, which are commands formed by grouping subcommands together. The
567 commands typically come from the current namespace when the ensemble
568 was created, though this is configurable. Note that there may be any
569 number of ensembles associated with any namespace (including none,
570 which is true of all namespaces by default), though all the ensembles
571 associated with a namespace are deleted when that namespace is deleted.
572 The link between an ensemble command and its namespace is maintained
573 however the ensemble is renamed.
574
575 Three subcommands of the namespace ensemble command are defined:
576
577 namespace ensemble create ?option value ...?
578 Creates a new ensemble command linked to the current namespace,
579 returning the fully qualified name of the command created. The
580 arguments to namespace ensemble create allow the configuration
581 of the command as if with the namespace ensemble configure com‐
582 mand. If not overridden with the -command option, this command
583 creates an ensemble with exactly the same name as the linked
584 namespace. See the section ENSEMBLE OPTIONS below for a full
585 list of options supported and their effects.
586
587 namespace ensemble configure command ?option? ?value ...?
588 Retrieves the value of an option associated with the ensemble
589 command named command, or updates some options associated with
590 that ensemble command. See the section ENSEMBLE OPTIONS below
591 for a full list of options supported and their effects.
592
593 namespace ensemble exists command
594 Returns a boolean value that describes whether the command com‐
595 mand exists and is an ensemble command. This command only ever
596 returns an error if the number of arguments to the command is
597 wrong.
598
599 When called, an ensemble command takes its first argument and looks it
600 up (according to the rules described below) to discover a list of words
601 to replace the ensemble command and subcommand with. The resulting
602 list of words is then evaluated (with no further substitutions) as if
603 that was what was typed originally (i.e. by passing the list of words
604 through Tcl_EvalObjv) and returning the result of the command. Note
605 that it is legal to make the target of an ensemble rewrite be another
606 (or even the same) ensemble command. The ensemble command will not be
607 visible through the use of the uplevel or info level commands.
608
609 ENSEMBLE OPTIONS
610 The following options, supported by the namespace ensemble create and
611 namespace ensemble configure commands, control how an ensemble command
612 behaves:
613
614 -map When non-empty, this option supplies a dictionary that provides
615 a mapping from subcommand names to a list of prefix words to
616 substitute in place of the ensemble command and subcommand words
617 (in a manner similar to an alias created with interp alias; the
618 words are not reparsed after substitution); if the first word of
619 any target is not fully qualified when set, it is assumed to be
620 relative to the current namespace and changed to be exactly that
621 (that is, it is always fully qualified when read). When this op‐
622 tion is empty, the mapping will be from the local name of the
623 subcommand to its fully-qualified name. Note that when this op‐
624 tion is non-empty and the -subcommands option is empty, the en‐
625 semble subcommand names will be exactly those words that have
626 mappings in the dictionary.
627
628 -parameters
629 This option gives a list of named arguments (the names being │
630 used during generation of error messages) that are passed by the │
631 caller of the ensemble between the name of the ensemble and the │
632 subcommand argument. By default, it is the empty list.
633
634 -prefixes
635 This option (which is enabled by default) controls whether the
636 ensemble command recognizes unambiguous prefixes of its subcom‐
637 mands. When turned off, the ensemble command requires exact
638 matching of subcommand names.
639
640 -subcommands
641 When non-empty, this option lists exactly what subcommands are
642 in the ensemble. The mapping for each of those commands will be
643 either whatever is defined in the -map option, or to the command
644 with the same name in the namespace linked to the ensemble. If
645 this option is empty, the subcommands of the namespace will ei‐
646 ther be the keys of the dictionary listed in the -map option or
647 the exported commands of the linked namespace at the time of the
648 invocation of the ensemble command.
649
650 -unknown
651 When non-empty, this option provides a partial command (to which
652 all the words that are arguments to the ensemble command, in‐
653 cluding the fully-qualified name of the ensemble, are appended)
654 to handle the case where an ensemble subcommand is not recog‐
655 nized and would otherwise generate an error. When empty (the
656 default) an error (in the style of Tcl_GetIndexFromObj) is gen‐
657 erated whenever the ensemble is unable to determine how to im‐
658 plement a particular subcommand. See UNKNOWN HANDLER BEHAVIOUR
659 for more details.
660
661 The following extra option is allowed by namespace ensemble create:
662
663 -command
664 This write-only option allows the name of the ensemble created
665 by namespace ensemble create to be anything in any existing
666 namespace. The default value for this option is the fully-qual‐
667 ified name of the namespace in which the namespace ensemble cre‐
668 ate command is invoked.
669
670 The following extra option is allowed by namespace ensemble configure:
671
672 -namespace
673 This read-only option allows the retrieval of the fully-quali‐
674 fied name of the namespace which the ensemble was created
675 within.
676
677 UNKNOWN HANDLER BEHAVIOUR
678 If an unknown handler is specified for an ensemble, that handler is
679 called when the ensemble command would otherwise return an error due to
680 it being unable to decide which subcommand to invoke. The exact condi‐
681 tions under which that occurs are controlled by the -subcommands, -map
682 and -prefixes options as described above.
683
684 To execute the unknown handler, the ensemble mechanism takes the speci‐
685 fied -unknown option and appends each argument of the attempted ensem‐
686 ble command invocation (including the ensemble command itself, ex‐
687 pressed as a fully qualified name). It invokes the resulting command in
688 the scope of the attempted call. If the execution of the unknown han‐
689 dler terminates normally, the ensemble engine reparses the subcommand
690 (as described below) and tries to dispatch it again, which is ideal for
691 when the ensemble's configuration has been updated by the unknown sub‐
692 command handler. Any other kind of termination of the unknown handler
693 is treated as an error.
694
695 The result of the unknown handler is expected to be a list (it is an
696 error if it is not). If the list is an empty list, the ensemble command
697 attempts to look up the original subcommand again and, if it is not
698 found this time, an error will be generated just as if the -unknown
699 handler was not there (i.e. for any particular invocation of an ensem‐
700 ble, its unknown handler will be called at most once.) This makes it
701 easy for the unknown handler to update the ensemble or its backing
702 namespace so as to provide an implementation of the desired subcommand
703 and reparse.
704
705 When the result is a non-empty list, the words of that list are used to
706 replace the ensemble command and subcommand, just as if they had been
707 looked up in the -map. It is up to the unknown handler to supply all
708 namespace qualifiers if the implementing subcommand is not in the name‐
709 space of the caller of the ensemble command. Also note that when ensem‐
710 ble commands are chained (e.g. if you make one of the commands that im‐
711 plement an ensemble subcommand into an ensemble, in a manner similar to
712 the text widget's tag and mark subcommands) then the rewrite happens in
713 the context of the caller of the outermost ensemble. That is to say
714 that ensembles do not in themselves place any namespace contexts on the
715 Tcl call stack.
716
717 Where an empty -unknown handler is given (the default), the ensemble
718 command will generate an error message based on the list of commands
719 that the ensemble has defined (formatted similarly to the error message
720 from Tcl_GetIndexFromObj). This is the error that will be thrown when
721 the subcommand is still not recognized during reparsing. It is also an
722 error for an -unknown handler to delete its namespace.
723
725 Create a namespace containing a variable and an exported command:
726
727 namespace eval foo {
728 variable bar 0
729 proc grill {} {
730 variable bar
731 puts "called [incr bar] times"
732 }
733 namespace export grill
734 }
735
736 Call the command defined in the previous example in various ways.
737
738 # Direct call
739 ::foo::grill
740
741 # Use the command resolution path to find the name
742 namespace eval boo {
743 namespace path ::foo
744 grill
745 }
746
747 # Import into current namespace, then call local alias
748 namespace import foo::grill
749 grill
750
751 # Create two ensembles, one with the default name and one with a
752 # specified name. Then call through the ensembles.
753 namespace eval foo {
754 namespace ensemble create
755 namespace ensemble create -command ::foobar
756 }
757 foo grill
758 foobar grill
759
760 Look up where the command imported in the previous example came from:
761
762 puts "grill came from [namespace origin grill]"
763
764 Remove all imported commands from the current namespace:
765
766 namespace forget {*}[namespace import]
767
768 Create an ensemble for simple working with numbers, using the -parame‐ │
769 ters option to allow the operator to be put between the first and sec‐ │
770 ond arguments. │
771
772 namespace eval do { │
773 namespace export * │
774 namespace ensemble create -parameters x │
775 proc plus {x y} {expr { $x + $y }} │
776 proc minus {x y} {expr { $x - $y }} │
777 } │
778
779 # In use, the ensemble works like this: │
780 puts [do 1 plus [do 9 minus 7]] │
781
783 interp(n), upvar(n), variable(n)
784
786 command, ensemble, exported, internal, variable
787
788
789
790Tcl 8.5 namespace(n)