TIP #470: Reliable Access to OO Definition Context Object

Title:Reliable Access to OO Definition Context Object
Version:$Revision: 1.4 $
Author:Donal Fellows <dkf at users dot sf dot net>
Created:Sunday, 23 April 2017
Keywords:TclOO, metaprogramming


This TIP makes it easier for people to write procedures to extend TclOO's definition sublanguage.


One of the fundamental features of Tcl is that you can extend it with more capabilities by writing your own procedures (and other commands, if you prefer the C API). However, it is somewhat awkward to do so when using TclOO, as the oo::define and oo::objdefine commands don't make it easy to find out what the context class or object is.

For example, in the oo::util package of Tcllib, the code for discovering what the context class is includes this [1]:

    # Get the name of the current class or class delegate 
    set cls [namespace which [lindex [info level -1] 1]]

That is ugly, and won't even work reliably for getting the context object in oo::objdefine as that can be entered into by multiple paths (i.e., there's a shortcut from oo::define).

Proposed Change

I propose to make the existing self command in oo::define, when invoked without arguments, return the context class (provided it is evaluated in the correct stack frame, as usual with definition commands). Similarly, I also propose to add a self command to the oo::objdefine system that takes no arguments and returns the context object.

This will enable to code listed above in the Rationale to become:

    # Get the name of the current class or class delegate 
    set cls [uplevel 1 self]

In the C API, I propose adding a function:

Tcl_Object Tcl_GetDefineContextObject(Tcl_Interp *interp)

which will get the context object, or return NULL and put an error in the interpreter if there is no context object in the frame or the context object has been deleted. The functionality is that of TclOOGetDefineCmdContext in tclOODefineCmds.c [2], but the text of the error messages might be changed.


This document has been placed in the public domain.

Powered by Tcl[Index] [History] [HTML Format] [Source Format] [LaTeX Format] [Text Format] [XML Format] [*roff Format (experimental)] [RTF Format (experimental)]

TIP AutoGenerator - written by Donal K. Fellows