dict get?

 proc ::tcl::dict::get? {args} {

    try {                ::set x [dict get {*}$args]
    } on error message { ::set x {} }

    return $x
 }

 namespace ensemble configure dict -map [dict merge [namespace ensemble configure dict -map] {get? ::tcl::dict::get?}]

This should check the error message before unilaterally clearing the return value, but well, it work like this.


AMG: Here is an improved version of the above that does check which error occurs.

proc ::tcl::dict::get? {args} {
    ::try {get {*}$args} trap {TCL LOOKUP DICT} {} {}
}
namespace ensemble configure dict -map [dict merge\
        [namespace ensemble configure dict -map]\
        {get? ::tcl::dict::get?}]

Now let's add a default value, implemented using argparse so as to allow the variadic arguments to be in the middle of the argument list:

proc ::tcl::dict::getwithdefault {args} {
    ::argparse {dictionary keys* default}
    ::try {
        get $dictionary {*}$keys
    } trap {TCL LOOKUP DICT} {} {
        ::set default
    }
}
namespace ensemble configure dict -map [dict merge\
        [namespace ensemble configure dict -map]\
        {getwithdefault ::tcl::dict::getwithdefault}]

See also ensemble extend for details on adding commands to an ensemble.


kpv See also tip 342