Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Type annotation for Type Annotation

Tags:

My question is: What type annotation do you use when a function is taking a type annotation as an argument?

Why am I taking a type annotation as an argument?

I have a function that tries to parse a string based on a type annotation. E.g.

def get_appropriate_type_converter(type_annotation) -> Callable[[str], 'type_annotation']:

e.g. get_appropriate_type_converter(Dict[str, int])("aaa:3,bbb:4") == dict(aaa=3, bbb=4)

And I want to type annotate this function.

like image 520
Peter Avatar asked Aug 19 '20 19:08

Peter


1 Answers

from some investigation we can detect what type something like Dict[str,int] is:

>>> from typing import *
>>> x = Dict[str, int]
>>> type(x)
<class 'typing._GenericAlias'>
>>> y = Union[str, float]
>>> type(y)
<class 'typing._GenericAlias'>

So my guess is that you would use the annotation typing._GenericAlias to indicate you take a type alias, I don't have the tools on me to see if a linter confirms this.

like image 170
Tadhg McDonald-Jensen Avatar answered Oct 12 '22 08:10

Tadhg McDonald-Jensen