As Python supports type annotations, it enables a static typing discipline. When working with the AST produced by the ast
module, it strikes me that given such discipline all types could be inferred, there should be no need for type annotations. Given a static typing pragma (perhaps a comment at top of the code file), an additional layer of logic in the parser could traverse the AST to determine types of all variables.
For example, take this snippet of code from the Mypy website:
d = {} # type: Dict[str, int]
with open(sys.argv[1]) as f:
for s in f:
for word in re.sub('\W', ' ', s).split():
d[word] = d.get(word, 0) + 1
The dict d
and its keys and values are typed with a comment, but the type could be inferred from the looping that follows: s
is a str
if it is in f
, the content read from a file; and the dict item value is an int
because that's what the assignment expression returns.
Is it the case that performing such analysis of the code is generally too expensive for static typing to be inferred, or am I missing something else?
Please note that this question does not relate to the discussion regarding dynamic versus static typing, or optional typing. My point is about type inferrence when the programmer agrees to static typing.
x = eval(input("Enter any value:"))
, what is the type of x? – Kevineval
could produce. I mean, where there is a will, there is a way. Drawing attention to such edge cases with zero discussion of the topic presented, is that really meant to be helpful? I have since learnt that what my question refers to is called "structured typing" as opposed to "nominal". So the idea is not new and the question not unreasonable. Particularly in the context of a language like Python, where it's understandable a user may like to have static typing without annotations, given how the language has been used hitherto. – Theo d'Ory = random.choice([1, "foo"])
? – Kevin