Generic factory class in Python

Consider a class with the following structure:

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

If I take it Foo, I will Foo.Meta.goo == 1. What is the right way to create an abstract factory class foo_factoryso that I can call:

>>> Clazz = foo_factory(goo=2)
>>> Clazz
<class '__main__.Foo'>
>>> Clazz.Meta.goo
2
+4
source share
2 answers

You can use the assignment:

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

I created classes as a nested structure; you can use calls type(), but I find it more readable.

Or you can use another name to close:

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

In any case, the created classes are recreated (they are not shared between calls).

+4
source

, . "OMG WHY?????";)

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

Source: https://habr.com/ru/post/1616725/


All Articles