4

In Python3 it's possible to add the type to the arguments of a function:

def foo(bar: str = "default") -> str:
    """
    @param bar: a textual value
    """
    return "test"

Now I got two questions. First, how can you do that for a callback function? Meaning, how to define the signature of that callback in the function header?

def foo(callback) -> str:
    """
    @param callback: function(value: str) -> str
    """
    # calculate some intermediate stuff
    my_var = ...    
    return callback(my_var)

Second, how to do that for tuples. This would include the defining that the value is of type tuple and should have two values (no triple etc.).

def foo(value) -> str:
    """
    @param value: tuple of strings
    """

    v1, v2 = value
    return v1 + v2

Thanks for your comments and answers.

5
  • 3
    See docs.python.org/3/library/typing.html Commented Dec 1, 2017 at 12:29
  • A callback is a callable Commented Dec 1, 2017 at 12:29
  • but a callback must satisfy a signature in which is needs to be invoked. See example above. Commented Dec 1, 2017 at 12:30
  • 1
    In your example callback annotation would be typing.Callable[[str], str] Commented Dec 1, 2017 at 12:32
  • One more problem: if you define a static method inside a class whereas that method has arguments of the same type/class, then that type is unknown ... Commented Dec 1, 2017 at 12:36

1 Answer 1

2

To specify the signature of your callback function, you can use Callable, like this:

from typing import Callable


def foo(callback: Callable[[str], str]) -> str:
    # calculate some intermediate stuff
    my_var = '...'
    return callback(my_var)

For a tuple of two strings, you can use:

from typing import Tuple


def foo(value: Tuple[str, str]) -> str:
    v1, v2 = value
    return v1 + v2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.