Tinker
Tinker

Reputation: 4525

How do I create a Factory method in Python that generates different classes?

Currently, I have the following:

class ConfirmStepAView(UpdateProcessView):
    form_class = ConfirmationForm

    def validate(self):
        if not self.process.A: 
            raise ValidationError

class ConfirmStepBView(UpdateProcessView):
    form_class = ConfirmationForm

    def validate(self):
        if not self.process.B: 
            raise ValidationError

# Usage: 
flow.View(ConfirmStepAView)
flow.View(ConfirmStepBView)

How can I write a factory method that generates these classes on the fly so I can do something like this?

flow.View(ConfirmStepViewFactory('A'))
flow.View(ConfirmStepViewFactory('B'))
flow.View(ConfirmStepViewFactory('Something'))
flow.View(ConfirmStepViewFactory('Else'))

Note: I have to use this format because I am working with a third part library.

Upvotes: 1

Views: 58

Answers (1)

cs95
cs95

Reputation: 402363

This is a common pattern. You can utilise closures in python to dynamically create and return your class.

def make_ConfirmStepView(attribute):
    class ConfirmStepView(UpdateProcessView):
        form_class = ConfirmationForm

        def validate(self):
            if not getattr(self.process, attribute): 
                raise ValidationError

    return ConfirmStepView

flow.View(make_ConfirmStepView('A'))
flow.View(make_ConfirmStepView('B'))
flow.View(make_ConfirmStepView('Something'))
flow.View(make_ConfirmStepView('Else'))

Upvotes: 1

Related Questions