Hacker News new | ask | show | jobs
by hythloday 5169 days ago
But you don't have to write your callbacks in reverse order in python:

  >>> def fight(batman_wins):
  ...     def t(): return "pow"
  ...     def f(): return "oof"
  ...     def b(msg): print msg
  ...     # if_but not defined at this point
  ...     if_but(lambda: batman_wins, t, f, b)
  ...
  >>> def if_but(cond, true, false, but):
  ...     if cond():
  ...       v = true()
  ...     else:
  ...       v = false()
  ...     but(v)
  ...
  >>> fight(True)
  pow
  >>> fight(False)
  oof
Sure, if you want to call if_but outside a function, it has to be defined, but inside a function (as in your example, and in 99% of python development that doesn't occur in a REPL) x() is effectively globals()['x'](). Have I totally misunderstood your point?
1 comments

This problem is indeed less severe when the names are defined in a non-local namespace (inside a class, or as globals).

But callback-style often appeals to defining very-local callback code. In fact, it would be anonymous in languages that support it, but it is forced to not only be given a name, but also potentially clutter some namespace (or be written in reverse order).

Consider having every for/while loop, or every "if" require giving a name to the code block[s] within it. It sounds insane. The same doesn't sound insane for library functions, but in my opinion that's really just because everybody's used to this limitation.

When I moved from Python to Haskell, one of the many joys was that I could stick an anonymous code block anywhere so easily.

Thanks for the explanation, that makes sense.