Given the following snippet in python 3
def foo() -> List[X]: pass
class X:
def bar(self) -> MYTYPE: pass
for the following expression:
[x.bar() for x in foo()]
Can I utilize mypy
package to correctly parse the AST of the expression above and guess the type of the result is List[MYTYPE]
?
If can not, what's my best choice? any ideas/packages to recommend?
Yes, it will infer it. Here's a demo:
from typing import List
class MyType:
pass
class X:
def bar(self) -> MyType: pass
def foo() -> List[X]: pass # note the square brackets
bars = [x.bar() for x in foo()]
reveal_type(bars)
Then when you run mypy script.py
in a terminal you will see a message:
Revealed type is 'builtins.list[script.MyType*]'
Documentation about reveal_type
here.
By the way there was a small problem with your code, it should be List[X]
not List(X)
.
PyCharm will also recognise the types. bars.
will give autocomplete options for list methods, and bars[0].
will give options for MyType
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments