Hacker News new | past | comments | ask | show | jobs | submit login

Ah I see what you mean (I wrote macros in Clojure years ago). Yep that would do it, but would require an AST-rewriting decorator in Python.

That’s an interesting thought! I guess I just found a good project to play on during the holidays. I wonder if something like this would work:

    with matching(expr) as m:

        def do_for_pattern(v):

        def catchall(v):

Something like this?

  class matching:
      def __init__(self, expr):
          self.expr = expr
          self.patterns = []
          self.result = None
      def __call__(self, pattern):
          def _inner(func):
              self.patterns.append((pattern, func))
              return func
          return _inner
      def __enter__(self):
          return self
      def __exit__(self, *args):
          for pattern, func in self.patterns:
              if pattern.match(self.expr):
                  self.result = func(self.expr)

Ooh that is a really nice syntax. And it would definitely work as it is essentially:

    m(pattern)(lambda v: ...)
Design would be to consider the execution of the match and dispatch as a “cleanup” of the specification created in the block. Which makes a ton of sense in a weird way.

May end up using this, or one of us should send a PR to the OP!

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact