pytype icon indicating copy to clipboard operation
pytype copied to clipboard

Using Type as a generic dictionary callable

Open theahura opened this issue 3 years ago • 2 comments

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

theahura avatar Aug 15 '22 22:08 theahura

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.

rchen152 avatar Aug 18 '22 22:08 rchen152

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 =(

rchen152 avatar Aug 18 '22 23:08 rchen152