Hacker News new | ask | show | jobs
by visarga 2049 days ago
> I never once recall an instant where I was saying "Uh uh, this type signature is driving me craaazy"

For example, this is ugly in Python:

def handler(on_error: Callable[[int, Exception], None]):

3 comments

Alternatively a Protocol can be used instead of Callable

  from typing import Protocol

  class ErrorHandler(Protocol):
      def __call__(self, p0: int, p1: Exception) -> None: ...

  def handler(on_error: ErrorHandler): ...
It doesn't matter if you have the types ascribed explicitly or not. In the end, the developer needs to know the types in both cases anyways. Otherwise, if they don't know the types, they will pass in a callable that expects the wrong types (for example they mix up [int, Exception] to [Exception, int]) and now you just have a runtime error.

If anything, having type signatures like that are a good thing! If you think they are too complicated/ugly or driving you crazy, then you have an incentive to improve them. In many languages, callbacks are now considered bad style and that's good! Hiding the type signature does not make the problem go away, you just move it into the future where it will bite you even more.

What's the alternative?

No type signature? Or documentation in another file somewhere else guaranteed to be out of sync, difficult to find and not enforced by the compiler? No thanks to either of them.