i'm trying generate javascript based on type annotations have provided in on python functions using signature()
function in inspect
module.
this part works expect when type simple builtin class:
import inspect def my_function() -> dict: pass signature = inspect.signature(my_function) signature.return_annotation dict # true
though i'm not sure how unwrap , inspect more complex annotations e.g:
from typing import list import inspect def my_function() -> list[int]: pass signature = inspect.signature(my_function) signature.return_annotation list[int] # false
again similar problem forward referencing custom class:
def my_function() -> list['user']: pass ... signature.return_annotation # typing.list[_forwardref('user')]
what i'm looking out - can branch appropriately while generating javascript:
type = signature.return_annotation... # list member_type = signature.return_annotation... # int / 'user'
thanks.
list
not map of types genericmeta
, despite syntax. each access generates new instance:
>>> [ id(list[str]) in range(3) ] [33105112, 33106872, 33046936]
this means list[int] not list[int]
. compare 2 instances, have multiple options:
- use
==
, i.e.,signature.return_annotation == list[int]
. store instance of type in global variable , check against that, i.e.,
a = list[int] def foo() -> a: pass inspect.signature(foo).return_annotation
use
issubclass
. typing module defines that. note might more you'd like, make sure read_typealias
documentation if use this.- check against
list
, read contents yourself. though property internal, unlikely implementation change soon:list[int].__args__[0]
contains type argument starting python 3.5.2, , in earlier versions,list[int].__parameters__[0]
.
if you'd write generic code exporter, last option best. if need cover specific use case, i'd go using ==
.
Comments
Post a Comment