auto
is an inferred type but it's still a static type. The difference is that the compiler knows what every value's type is in a statically-typed language (including the actual type of the auto
values), but in a dynamically-typed language the type is only known at runtime. Also, variables in a statically-typed language have one fixed type even if they're declared with auto
, but variables in a dynamic language can change types during program execution.
Consider the following C++ code:
int main() {
auto foo = "hello";
puts(foo / 5);
}
This code will fail to compile, because you can't divide a const char*
by an integer. Notably, even though foo
is declared with type auto
, the compiler knows that it's actual type is const char*
. In fact, using const char* foo = "hello"
gives the exact same semantics, auto
is just syntax sugar for the programmer.
Now, consider the corresponding Python code:
def main():
foo = "hello"
print(foo / 5)
This code will fail at runtime if/when main
is called. Python doesn't statically check types, so while you also can't divide a string by an integer, it's only detected when foo / 5
actually runs.
Failing at compile-time is generally regarded as better, but there are other drawbacks to static types (see: "What are the pros and cons of static typing?"). For example, you can't assign an auto
variable a value of a different type than it was declared with, because it still has a single consistent ("static") type, the type is just inferred.
int main() {
// This is OK, `foo` has type `const char*`
auto foo = "hello";
foo = "world";
// So is this, `bar` has type `int`
auto bar = 42;
bar = 45;
// However, this doesn't compile, because `foo` has already been assigned type `const char*`
foo = 48;
}
But you can assign differently-typed values the same variable in a language with dynamic types, because foo
has no consistent type (it's type is "dynamic").
# This code runs as expected, with no errors
foo = "hello"
print(foo)
foo = 42
print(foo / 2)
foo
is a templated function that can depend on its' parameter values. $\endgroup$