[IronPython] Monkey-patching CLR types

Jimmy Schementi Jimmy.Schementi at microsoft.com
Sun Feb 14 23:06:24 CET 2010


(Yes, I'm asking a question this time =P)

I want to know my options for adding functionality to an existing CLR type. Specifically I want to make hooking DOM events cleaner: in Silverlight today you cannot hook DOM events with the standard += syntax that IronPython uses for CLR events:

    object.onclick += foo

Instead you must do this:

    object.AttachEvent("onclick", EventHandler[HtmlEventArgs](foo))

In IronRuby I fixed that by just monkey-patching System.Windows.Browser.HtmlObject, but in IronPython I cannot monkey-patch built-in types. However, I do something similar with accessing DOM properties (instead of element.GetProperty("innerHTML") it's just element.innerHTML) with DLR's ExtensionType, which is the same way IronPython exposes special methods on CLR types as well:
 
    [assembly: ExtensionType(typeof(HtmlElement), typeof(HtmlElementExtension))]
    public static class HtmlElementExtension {
        [SpecialName]
        public static object GetBoundMember(HtmlElement element, string name) {
            return element.GetProperty(name);
        }
    }

But after looking through Python's Binder and the DLR's ActionBinder for how they use ExtensionTypes, I couldn't get a definitive answer on how to capture an method call plus an operator. Any ideas?

~Jimmy




More information about the Ironpython-users mailing list