John Lam 1997 — 2026

Method interception made easy

This morning on the train ride into Toronto, I decided to hack up a piece of code that emulates in Python what took me nearly 6 months using C++ and the CLR. One of the wicked cool features of Python is the ability to dynamically bind and unbind methods to class attributes. An attribute is roughly analogous to a class member in .NET.

This sample adds “execute once” semantics to all methods of a class that belongs to the ExecuteOnce metaclass. There’s a couple of interesting things to point out in the code:

  1. The StaticCallable class exists only to let me call a static method. This hack seems rather crufty in a language like Python that excels at reducing friction. Update: not needed anymore in Python 2.2+.
  2. The sentinel method is the method that gets called in place of the “real” method that I’m intercepting. In it, I check for the existence of a sentinel flag that marks whether that method has executed already.

Here’s the code in all of its glory. Once again, marvel at the elegence of this technique:

# Metaclass that performs execute-once semantics

class ExecuteOnce(type):
    def sentinel(methodname):
        def _method(self, *arg1, **argd):
            sentinelname = '_shadow_%s_executed' % methodname
            shadowmethodname = '_shadow_%s' % methodname

            if hasattr(self, sentinelname) == False:
                setattr(self, sentinelname, True)
                return getattr(self, shadowmethodname)(*arg1, **argd)
            else:
                return

        return _method

    sentinel = staticmethod(sentinel)

    def __new__(cls, classname, bases, classdict):
        for attr, item in classdict.items():
            if callable(item):
                classdict['_shadow_%s' % attr] = item
                classdict[attr] = ExecuteOnce.sentinel(attr)

        return type.__new__(cls, classname, bases, classdict)

class Test(object):
    __metaclass__ = ExecuteOnce
    def method1(self):
        print "In method1"

t = Test()
t.method1()
t.method1()
t.method1()

Update: I’ve incorporated Alan Hecht’s suggestion from my comments to fix a bug error in my code and eliminate the need for the StaticCallable helper class.

9 archived reader comments

Gordon Weakliem (2004-09-20)

The classdict[attr] = sentinel(attr) line is throwing NameError: global name ‘sentinel’ is not defined

Alan Hecht (2004-09-20)

I think I found a way to obviate the need for the class Callable.

Try using “sentinel = staticmethod(sentinel)” instead of “sentinel = Callable(sentinel)”, and replace the line “classdict[attr] = sentinel(attr)” with “classdict[attr] = ExecuteOnce.sentinel(attr)”. This also seems to fix the exception as well.

I would post the code except that the indentation gets removed which makes it unreadable & unrunnable.

Moi (2004-09-21)

Is it just me or does anyone else using IE get odd displays when reading this blog? Sometimes when I scroll down bits of the text are not displayed (I mean, like the top half of some lines of text, not necessarily entire paragraphs).

Daniel (2004-09-22)

So are you programming in C++ without boost? Isn’t that a bit foolish?

http://www.boost.org/libs/thread/doc/once.html

It took me a minute to find that. 6 months!

Daniel (2004-09-22)

OK, I’m a complete moron - you’re running the method once per object, not only once overall. But I still don’t see what would take 6 months. Were you rewriting the object code?

John Lam (2004-09-22)

I spent 6 months implementing generic method interception for the CLR by dynamically replacing method bodies at JIT compilation time.

Boost wouldn’t have helped me there, nor would boost let me add execute once semantics to existing code without recompiling / modifying source.

Dilip (2004-09-22)

You are spawning ideas! Somebody thought it fit to do this stuff in Javascript :-)

http://w3future.com/weblog/2004/09/22.xml#closuresForAnonymousStorage

Daniel (2004-09-22)

Thanks for your reply. Sorry for being so hasty.

Anyway, if you haven’t seen it, you might be interested in Nemerle (www.nemerle.org) which has meta-programming features for doing exactly this kind of thing. You can write a macro do get something like this:

[ExecuteOnce] class Test { method1() : void { print “In method1” } }

Of course, it’s all experimental, and you can only use Nemerle meta-programming abilities on Nemerle code - but because it’s .NET, you can use inherit from an object written in another language (I think, I haven’t looked into it in much detail). I might try writing this sometime.

Daniel (2004-09-22)

Well, I’ve written it. It took me longer than it should have because I’ve very little experience with Nemerle (or .Net for that matter). I also have no idea how to do indentation in your comment field, so it’s pretty unreadable, and you probably might not be remotely interested, so sorry if that’s the case.

It’s compile-time, not dynamic, but then, this isn’t a dynamic language so that’s what you’d expect.

It doesn’t change methods in the base class. I think that’s possible by creating new methods which calls the method in the base class, but I haven’t implemented that yet. Here goes:

using Nemerle.Compiler; using Nemerle.Collections;

// Use the macro on a class after it has been typed. [Nemerle.MacroUsage (Nemerle.MacroPhase.WithTypedMembers, Nemerle.MacroTargets.Class)] macro ExecuteOnce(ty : TypeBuilder) { // Get a list of the methods in the class def methods = ty.GetMethods( BindingFlags.Public %| BindingFlags.NonPublic %| BindingFlags.Instance %| BindingFlags.DeclaredOnly);

foreach(m : IMethod in methods) { // Generate a variable name that won’t clash with existing names. def variableName = Macros.UseSiteSymbol(Util.tmpname(m.Name));

// Declare it. ty.Define(<[ decl: private mutable $(variableName : name) : bool = true; ]>);

// Rewrite the Body of the method. def m = (m :> NemerleMethod); m.Body = <[ when($(variableName : name)) { $(variableName : name) = false; $(m.Body); }; ]>; }; }