James Tauber

journeyman of some

blog > 2006 > 05 >

James Tauber's Blog 2006/05/14

Class Definitions Inside Functions

For a while, I've been defining functions in Python that define other functions and return them, taking advantage of lexical scoping and the first-class status of functions:

def foo(x):
    def bar(y):
        return x + y
    return bar

(yes, I realise you can also do this with a lambda expression)

But it all of a sudden occurred to me that you can probably define parameterised classes within functions and return them. Sure, enough, you can:

def foo(x):
    class bar:
        def __init__(self, y):
            self.z = x + y
    return bar

So foo isn't a factory producing objects, it's a factory producing classes.

This probably isn't news to most of you, but I think it's pretty cool that this works! Looking back, I can think of heaps of times I've wanted to parameterise classes and this would have been perfect.

by jtauber : Created on May 14, 2006 : Last modified May 14, 2006 : 4 comments (permalink)