What's the type for functions used as a dictionary value?

Viewed 38
Map: dict[str, object] = {
    "image" : Image.generate,
    "video" : Video.generate,
}

Here, generate(json) is a function in both cases. However I'm getting a typehint error that "object" not callable mypy(error). What should be the appropriate type instead of object for the Map?

1 Answers

You can use dict[str,Callable] to allow any callable object as a value, but you might want to be more specific. At the very least, it sounds like the function must return a single string (the resulting JSON value), so you can write

dict[str, Callable[[...], str]]

to allow functions that take arbitrary arguments and return a str. If you know more about what the function can accept, you can replace ... with one or more specific argument types.

Related