IronPython - high order functions as decorators for AOP

by DotNetNerd 20. September 2009 13:58

One of my favorite features from when I was playing around with F# was high order functions. A high order function is quite simply a function that takes a function as an argument and returnes a function. A basic sample just to get the point accross could be:

def Outer():
    innerText = "Hey dude! "
    def Inner(text):
        print innerText + text
    return Inner

myfunc = Outer()
myfunc("My function was called successfully")

This technique can be quite useful when composing functions, but also to wrap code and handle cross cutting concerns (e.g. like logging) through Aspect Oriented Programming. IronPython takes this concept a bit farther through what is called decorators. A decorator is to some extent similar to an attribute, and can be used to do AOP. Using decorators is as simple as defining a high order function and decorating the method that should be wrapped with @myHighOrderFunction like this:

def logging(function):
    def inner():
        print "Do pre call logging"
        function()
        print "Do post call logging"       
    return inner

@logging
def myfunc():
    print "Could do what interesting stuff you like"   
   
myfunc()

As you can see from the code it makes for a very straight foreward and elegant way og doing AOP.

UPDATE: I stumbled across this video with DevHawk where he actually shows a similar example during his talks here in DK.

Tags: ,

Who am I?

My name is Christian Holm Diget, and I work as an independent consultant, in Denmark, where I write code, give advice on architecture and help with training. On the side I get to do a bit of speaking and help with miscellaneous community events.

Some of my primary focus areas are code quality, programming languages and using new technologies to provide value.

Microsoft Certified Professional Developer

Microsoft Most Valuable Professional

Month List

bedava tv izle