Yuval Adam
Yuval Adam

Reputation: 165242

Generic class factory in Python

Consider a class with the following structure:

class Foo(object):
    # ...
    class Meta:
        goo = 1

If I take Foo I'll have Foo.Meta.goo == 1. What's the right way to create an abstract class factory foo_factory such that I can call:

>>> Clazz = foo_factory(goo=2)
>>> Clazz
<class '__main__.Foo'>
>>> Clazz.Meta.goo
2

Upvotes: 4

Views: 477

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122292

You could use assignment:

def foo_factory(goo):
    class Foo(object):
        class Meta:
            pass
    Foo.Meta.goo = goo
    return Foo

I created the classes as a nested structure; you could use type() calls but I find the above to be more readable.

Or you could use a different name for the closure:

def foo_factory(goo):
    goo_value = goo  # provide a closure with a non-conflicting name
    class Foo(object):
        class Meta:
            goo = goo_value
    return Foo

Either way, the classes produced are created anew (they are not shared between calls).

Upvotes: 4

viraptor
viraptor

Reputation: 34155

I'll trust you based on your points. My normal answer would be "OMG WHY?????" ;)

def foo_factory(goo):
    return type('Foo', (), {
        'Meta': type('Meta', (), {"goo": goo})
        })

Upvotes: 0

Related Questions