pytype
pytype copied to clipboard
Using Type as a generic dictionary callable
Is it possible to do something like this?
T = TypeVar('T')
LOG_FNS: Dict[Type[T], Callable[[T], Text] = {
list: log_list,
dict: log_dict,
str: log_str,
}
def log(x: Any):
if type(x) in LOG_FNS:
return LOG_FNS[type(x)](x)
return str(x)
right now this fails with:
Invalid type annotation 'Dict[Type[T], Callable[[T], Text]]' for LOG_FNS [invalid-annotation]
TypeVar(s) 'T' not in scope
For more details, see https://google.github.io/pytype/errors.html#invalid-annotation
Looks like the direct cause of the error is this line: https://github.com/google/pytype/blob/5609538482a90339bad78d44098a46bb723b586b/pytype/annotation_utils.py#L277 We're not allowing TypeVars that appear only once in a Callable.
Hmm, even if I get rid of the error, it looks like we don't substitute in the right type for T in this case =(