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.

The original post had 4 comments I'm in the process of migrating over.