2

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.

4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.