I'm trying to write an email delivery system. I have this enum, for all users, users that were logged in the last 3 months and 6 months:
class Receiver(enum.Enum):
ALL = "ALL"
THREE_MONTHS = "THREE_MONTHS"
SIX_MONTHS = "SIX_MONTHS"
The problem is, I'm trying to implement a Strategy pattern, so I need to enforce type checking. I know it is impossible by default, but ... any idea would be appreciated.
I need it to look like:
def send_to(Receiver.ALL):
pass
def send_to(Receiver.THREE_MONTHS):
pass
def send_to(Receiver.SIX_MONTHS):
pass
Yeah, I have Java background.
And the general sender would pass the value accordingly:
@api_view(["POST"])
def send_email(request):
email_to = request.data["emailTo"]
send_to(email_to)
Note: I do not want to write multiple if checks or switch cases. It totally contradicts with Open Closed principle of Uncle Bob, since if there is gonna be additional case, then the method must be modified. Absolutely unacceptable.
CodePudding user response:
Python doesn't have function overloading. What it does have is first-class function objects.
Create a dict
that maps Receiver
values to the appropriate function.
def send_to_all():
pass
def send_to_last_three_months():
pass
def send_to_last_six_months():
pass
senders = {
Receiver.ALL: send_to_all,
Receiver.THREE_MONTHS: send_to_last_three_months,
Receiver.SIX_MONTHS: send_to_last_six_months,
}
@api_view(["POST"])
def send_email(request):
email_to = request.data["emailTo"]
sender = senders[email_to]
sender()