Some language like Rust supports redefining variable in same scope.
IMHO, if python supports redefining variable and type inference,
it can achieve static typing without breaking existing code.
myVar = 100 # int, define
myVar = 200 # int
myVar = "foo" # str, redefine
def myFun(myPara): # para type determined when function called
...
myFun(100) # para: int
myFun("foo") # para: str
There are some Python dialects that support optimization based on type inference, EG shedskin.
But for turning on type inference for all programs run on CPython, consider what’ll happen if you put an int, a float, a str and an instance of a user-defined type into a list, and then iterate over that list.
I’ve not done a proof, but I suspect you’re going to find that doing 100% accurate type inference for all CPython programs is equivalent to the halting problem - IOW, unsolvable in a finite amount of time.
It depends how precise you want to be. For example, what is the inferred type of this function?
import random
def func():
return random.randrange(2) or "spam"
If you say str|int, you’re probably not wrong. But you could also say object, since it will always return an object. And if someone’s monkeypatched randrange to return something other than an integer, so too can this function, making it a bit awkward to predict anything.
What type does THIS function return? There’s no halting problem considerations here…
def func():
class Spam: pass
return Spam()
Is there any sane return type you could give this, other than object? Every time the function is called, it will return an object of a unique type.
Proper type inference is a balance between technical correctness and actual usefulness.
Or you can NOT grind at all, and just say that everything accepts and returns object. That’s my point: duck typing is perfectly valid typing, and it works for all programs without any grinding. You have a complete 100% guarantee, just looking at the syntax of the program, that every value is an object.
I don’t know what you’re expecting from type inference, but it definitely won’t be running Python hundreds of times faster. You may want to look into several completely unrelated concepts here, including type inference (see eg MyPy), JIT compilation (see eg PyPy), and some of the Faster CPython projects.
Simply knowing the data type of something is not going to suddenly make that kind of improvement, because if it did, it would already have been done.