Pythonista: Applying Python idiom to C# with attribute-builder pattern

Recently I’ve been looking into the way Google AppEngine lets you define properties from a “property class” and noticed a semi-metaprogramming pattern:

class Greeting(db.Model):
    author = db.UserProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)

Note how author, content and date looks like a normal variable with a class instance being assigned.

And recently I have been Diving into Python and was reading up on class instantiation and so I immediaty thought of this:

def buildAdder(num):
    def myAdder(x): return num + x
 
    return myAdder

This function lets me easily create functions (closures?) on-the-fly ala meta-programming, so I can create a class like this:

class MyClass:
    add1 = buildAdder(1)
    add2 = buildAdder(2)
    add3 = buildAdder(3)

And sure enoughs, MyClass now has 3 methods for adding 1, 2 and 3 respectively:

k = MyClass()
print k.add1(9)    # prints 10
print k.add2(8)    # prints 10
print k.add3(7)    # prints 10

And I suddenly realize that This pattern can easily be mimicked in C#!

Because in C# 3.5 we now have lambda functions and closures, this pattern can be repeated almost exactly the same way in C# by utilizing public Func fields:

class MyClass
{
    public Func<int, int> Add1 = buildAdder(1);
    public Func<int, int> Add2 = buildAdder(2);
    public Func<int, int> Add3 = buildAdder(3);
 
    static Func<int, int> buildAdder(int number)
    {
        return x => x + number;
    }
}

And then I can invoke the functions on MyClass just the same way:

var t = new MyClass();
Console.WriteLine(t.Add1(9));   // prints 10
Console.WriteLine(t.Add2(8));   // prints 10
Console.WriteLine(t.Add3(7));   // prints 10

C# is awesome!

However, classes in C# are immutable so they are not easily plugged-in and plugged-out like those in Python. It might take a lot more work to translate Django/AppEngine-style property builder pattern to C#.

There are also some performance implications to be concerned, but in some slow-start-doesn’t-matter scenarios this might prove to be useful.

Posted: May 23rd, 2009
Categories: Tutorials
Tags: , , , ,
Comments: 3 Comments.
Comments

[...] This is a follow up to last post on attribute-builder pattern. [...]

Comment from m3rlinez - May 24, 2009 at 10:52 am

Without the use of ‘Func’, I can define a delegate to accomplish the same thing too, right?

And without C#, is this the same thing as defining interfaces and use anonymous class to implement them in Java ? (http://stackoverflow.com/questions/443708/callback-functions-in-java/443741#443741)

I still can’t understand this Python’s beauty :(

Comment from chakrit - May 27, 2009 at 10:31 pm

Same… but its more elegant in Python less so in C# less so using delegate and even less so in Java.