Digging your sharp hooks in

Here's some code I wrote recently. And what I want to point out is.... Actually, I'll let you skim the code first:

  1. # begin
  2. class HookEventHandler(metaclass=abc.ABCMeta):
  3. def __init__(self, hook_event):
  4. self.hook_event = hook_event
  5. @abc.abstractmethod
  6. def process(self):
  7. pass
  8. def response(self, response_data):
  9. return HttpResponse(json.dumps(response_data), content_type='application/json')
  10. @classmethod
  11. def choose(cls, funnel_path):
  12. if funnel_path == '':
  13. return cls._HANDLER_CLASSES['test']
  14. for prefix, klass in cls._HANDLER_CLASSES.items():
  15. if funnel_path.startswith(prefix):
  16. return klass
  17. return None
  18. class TestFunnelHookEventHandler(HookEventHandler):
  19. def process(self):
  20. return self.response({'hook_event_id': self.hook_event.id})
  21. class TddPythonFunnelHookEventHandler(HookEventHandler):
  22. def process(self):
  23. response_data = {'hook_event_id': self.hook_event.id}
  24. try:
  25. body_data = self.hook_event.json()
  26. except json.JSONDecodeError:
  27. raise CFException(self.hook_event.id)
  28. if 'purchase' in body_data:
  29. if 'event' not in body_data:
  30. raise CFException(self.hook_event.id)
  31. if body_data['event'] == 'created':
  32. hp = HookPurchase.from_event(self.hook_event, body_data)
  33. response_data['hook_purchase_id'] = hp.id
  34. if hp.is_primary():
  35. send_register_email(hp.email, mk_register_url(hp.purchase.retrieval_key), 'Test-Driven Python + Bonuses')
  36. return self.response(response_data)
  37. HookEventHandler._HANDLER_CLASSES = {
  38. 'tdd-python': TddPythonFunnelHookEventHandler,
  39. 'test': TestFunnelHookEventHandler,
  40. }
  41. # end

(What's a "hook event", you ask? Doesn't matter. It's just an abstraction in my business logic.)

What I like about this code is that it uses several beyond-the-basics features of Python... and more importantly, leverages them all together.

That's a different game. When you learn Python at this level... it's FUN. Because you're able to express complex code patterns vividly, elegantly and easily...

And things just start to flow, in a way they never did before.

Looking over this code, how many interesting idioms and patterns can you identify? Making your own list of "beyond the basics" bullet points?

Because over the coming year, as you keep reading this newsletter, there's a lot I plan to tell you about. There just hasn't been good quality material out there for advanced and intermediate Python. Together, you and I are going to change that.

I think the key really is to have fun with it. And that is so easy to do in this language.

Have fun looking over the code. Let me know what's exciting that you find.