1

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'
2
  • Why does AFactory have to be a metaclass? Can't it be a function instead? Commented Sep 5, 2018 at 12:06
  • ok, it can be function or simple class, but how to pass dynamically NAME in A class? Commented Sep 5, 2018 at 12:13

1 Answer 1

2

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.