1

I want to create a service class that just has one instance, so should I make that class a singleton, or should I make the methods as classmethods?

class PromoService():

    @classmethod
    def create_promo(cls, promotion):
        #do stuff
        return promo

class DiscountPromoService(PromoService):

    @classmethod
    def create_promo(cls, promo, discount):
        promo = super(DiscountPromoService, cls).create_promo(promo)
        promo.discount = discount
        promo.save()
        return promo

The reason I don't want to create it as a module is because I would need to subclass my service. What is the most pythonic way to do this, the above-mentioned way or to make a singleton class?

Anubhav Agarwal
  • 1,982
  • 5
  • 28
  • 40

2 Answers2

1

If you want a singleton, go with a singleton. The pattern referenced here works well. You would simply need to do something like:

class PromoService():
    __metaclass__ = Singleton
mar10
  • 14,320
  • 5
  • 39
  • 64
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
1

Short answer: In my opinion it would work.

BUT, In pure pattern's sense, I have been wrestling with this question for a while:

Do python class methods and class attributes essentially behave like a Singleton?

  1. All instances of that class have no bearing on them
  2. Only class itself have access to them
  3. There is always one of them

Yes, pure Singleton Pattern comparison would fail plain and simple but surely its not far off?

Wouldn't call myself a python expert, so happy to know views on this be corrected on my assumptions.

Walaitki
  • 165
  • 2
  • 11