switch in python

Dal momento che switch non è implementato in python, si deve scrivere da sè.

Ci si basa sulla funzione __call__, e si utilizza un parametro condizione per il dato da testare. Quindi se esiste un callable di nome case_{condizione} all’interno della classe, verrà chiamato. Altrimenti si chiamerà la funzione default. Se non esiste nessuno dei due, ovviamente verrà sollevato un errore.

class switch:
    def __call__(self, condizione):
        if azione := getattr(self, f'case_{condizione}', None):
            return azione
        return self.default

Si crea quindi una sottoclasse di switch che implementa i vari casi.

class RevenueCatEventTypeSwitch(switch):
	def case_TEST(self):
		return "⚙️"
		
	def case_INITIAL_PURCHASE(self):
		return "🥉"
		
	def case_NON_RENEWING_PURCHASE(self):
		return "💎"
		
	def case_RENEWAL(self):
		return "💸"
		
	def case_PRODUCT_CHANGE(self):
		return "🔄"
		
	def case_CANCELLATION(self):
		return "❌"
		
	def case_UNCANCELLATION(self):
		return "✅"
		
	def case_BILLING_ISSUE(self):
		return "⚠️"
		
	def case_EXPIRATION(self):
		return "📉"
		
	def default(self):
		return "I don't know this event. Are you sure it is correct?"		

Per fare lo switch, quindi, si deve creare un oggetto RevenueCatEventTypeSwitch, e successivamente si chiama con la variabile per lo switch.

revenuecatswitch = RevenueCatEventTypeSwitch()
revenuecatswitch("PRODUCT_CHANGE")()

python_book6