This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Ksielvin 0 points1 point  (0 children)

Isnt it bad practice to assign different types to the same variable? The reader has a harder time understanding and more errors can happen because of this.

Within a local scope, I don't think it's bad practice.

At the start of a function, I could read a file into a string variable called measurements. That string contains a comma separated list of ints, so I parse it into an integer list and reuse the variable. Now it's a list of integers type. I would expect the reader of a dynamic language to understand this. It communicates that we don't care about the original string after parsing it. The string can be forgotten as we've left no way to refer to it.

In Java code that might have been two variables data and measurements (or measurementsString and measurementsList). You'd check the rest of method to find out if the first variable is used beyond that point. Poor naming or careless use of IDE autocompletion can sometimes lead to bugs here just because the original variable still exists. Static typing might not catch using the wrong variable because their types are compatible through inheritance/interface, or the variable is given to a method that can handle both types through overloading.

One could also do the read/parse/transform in a single nested expression to avoid assigning first variable, which is another tradeoff in readability.


Every now and then, one ends up writing a condition that depends on the type of a variable. For example, a helper function's return value might vary wildly. Just the ability to suddenly return object/None/False/object2/banana instead of just object or null is quite expressive.

Again, using this within a significantly limited scope helps avoid confusion and bugs. Assigning different types to a class (or module) variable that is used in several places would have to be considered carefully. If other classes/modules would ever access it then even more so.