0

Is there a Pythonic way of creating a Callable type like below (TypeScript and C# examples)?

TypeScript:

export type MyHandler = (paramOne: ClassOne, num: int) => null;

C#:

public delegate void MyHandler(ClassOne paramOne, int num);

Python:

MyHandler = Callable[[ClassOne, int], None]  # No lint errors...

While I'm not getting any lint errors in PyCharm; I haven't bothered running my snippet yet because of how not-Pythonic this feels. If this was going to be my own code for private consumption I don't think I would bother with creating this type, but it's going to be part of a library so I feel more obligated to create the type.

In usage, this type would show up in something like:

class SomeClass(ProbablyAnABC):
    # __init__ where self._handlers is created

    def register_handler(self, handler: MyHandler) -> None:
        self._handlers.append(handler)
Steven G.
  • 1,632
  • 1
  • 11
  • 14
  • 1
    Shouldn't that be `Callable[[ClassOne, int], None]`? I wouldn't get too worked up about it. The best thing you can do for readability is coming up with a more descriptive name than `MyHandler` – Patrick Haugh Mar 28 '18 at 01:20
  • 1
    In python you need to think about types yourself or try to execute your code https://stackoverflow.com/questions/2489669/function-parameter-types-in-python. Here is link about '_call_' it may be helpfull in your case https://stackoverflow.com/questions/5824881/python-call-special-method-practical-example. – Vayrex Mar 28 '18 at 01:49
  • @PatrickHaugh, thanks for catching that missing opening bracket; the current names are placeholder names for the question. – Steven G. Mar 28 '18 at 16:16
  • @Vayrex, thank you for those links they have been very helpful. – Steven G. Mar 28 '18 at 16:45

0 Answers0