3

I wrote a listener class that executes a programmer specified callback. The msg is provided as a callback argument. I realized that a programmer using the class will need to look at my code to see the structure of the msg.

Is there a way of providing type hints to callback functions. Or should i refactor my callback to be a notification of a message so the programmer can invoke a get function to get the actual msg after the notification. ( IDE help works in this case but the class is a little bit harder to use )

Alternatively i could just pass something generic in the argument like dictionary.

asked Apr 1, 2018 at 3:02

1 Answer 1

6

Regarding callback argument you can use python's typing module (docs). It'll be something like Callable which subscription syntax must always be used with exactly two values: the argument list and the return type:

def listener(callback: Callable[[int, str], int]):
 #do magic here
def callable(a: int, b: str) -> int:
 # user defined callable here

In this case, IDEs (like Pycharm and modern Jedi versions) will detect Callable typehints, and listener user won't have to look up callback structure.

Regarding if it's better to provide a dictionary or something else more generic is debatable and depends on actual use cases.

P.S. of course, typing module is not available out of the box in python2

answered Apr 1, 2018 at 3:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.