Hacker News new | ask | show | jobs
by teekert 3323 days ago
Am I being a complete noob that only knows Python (I am) if I ask: Why do you need to declare that something is a mut or string or whatever? Python doesn't seem to need such extra lines with obvious declarations.
3 comments

A couple important benefits (there are many others, as well as drawbacks) are

1) the compiler can then warn you when you violate your own declarations before the code is ever run. e.g. it can tell you that you've mutated something you said you didn't want to, or that you've taken the sum of an int and a list.

2) the compiler can guarantee certain things at compile time and thus eliminate the overhead of checking them at runtime. since a value in Python can be anything, before performing a string operation on a string the python runtime must first check that it is a string, while the runtime of a language like rust can assume that it is because that was guaranteed at compile time.

As others have mentioned, the idea is to have the compiler enforce certain things for you to reduce the chances of making an error. One illustrative way I've seen it explained is that if you accidentally make a variable immutable when you want it to be mutable, you get a very straightforward compiler error message saying something like "you can't mutate this variable since it's const; maybe you should make it mutable?". On the other hand, if you want a variable to be immutable but it's actually mutable and you change it, you can end up with all sorts of tricky bugs like race conditions which are much harder to debug.
Dynamic languages can convert types in runtime (so 1 + "f" = "1f") and not so many languages (not only dynamic) cares about mutability.
Supporting an addition operator that accepts mixed type operands has no relationship to being dynamically typed.
From quick check, it looks like Java can do this coercion, and it's not dynamically typed.
This is weak typing not dynamic typing.

1 + f in modern Python results in a ValueError.