timKa
timKa

Reputation: 177

implementing python metaclass for changing class level variable

Can you explain, how to implement AFactory class for doing this. It seems that I need to use metaclass but how? All my tries failed with KeyError

dct = {
    'key1': 'value1',
    'key2': 'value2'
}

class AFactory:
    pass

class A:
    NAME = ''
    VARIABLE = dct[NAME]

A1 = AFactory('key1')
a1 = A1()
assert a1.NAME == 'key1'
assert a1.VARIABLE == 'value1'

A2 = AFactory('key2')
a2 = A2()
assert a2.NAME == 'key2'
assert a2.VARIABLE == 'value2'

Upvotes: 1

Views: 58

Answers (1)

Aran-Fey
Aran-Fey

Reputation: 43166

It sounds like you really want a class factory, not a metaclass. (Yes, metaclasses are also class factories, but they're not the only ones.) So the easiest solution is to define AFactory as a function:

def AFactory(name):
    class A:
        NAME = name
        VARIABLE = dct[NAME]

    return A

If you really need a metaclass, you should implement an alternative constructor rather than trying to make the metaclass callable as AFactory(name):

class AFactory(type):
    @classmethod
    def make(mcs, name):
        clsname = 'A'
        bases = ()
        attrs = {
            'NAME': name,
            'VARIABLE': dct[name]
        }

        return mcs(clsname, bases, attrs)

Which you could then use like

A1 = AFactory.make('key1')

Upvotes: 2

Related Questions