In Python (and occasionally PHP) where variables do not have fixed types, I'll frequently perform 'type transformations' on a variable part-way through my code's logic. I'm not (necessarily) talking about simple casts, but about functions that change the type of a variable while leaving it basically representing the same value or data.
For example, I might write code like this when doing a web request, using the
response variable to store an addurlinfo object, then the string content of that object, and the dictionary returned by parsing the string as JSON:
response = urlopen(some_url) assert response.info().type == 'application/json' response = response.read() logger.debug('Received following JSON response: ' + response) response = json.loads(response) do_something(response)
(Okay, it's a slightly contrived example, but I think it demonstrates the idea fine). My feeling is that this is better than using three separate variable names because a) it conveys that the
response variable contains basically the same information, just 'transformed' into a different type, and b) it conveys that the earlier objects aren't going to be needed any further down the function, since by reassigning over their variable I've made them unavailable to later code.
The tradeoff, I guess, is that the reader could become confused about what type the variable is at any given moment.
Is this bad style, and should I be using three different variables in the above example instead of reassigning to one? Also, is this standard practice in dynamically typed languages, or not? I haven't seen enough of other people's code to know.