Is changing the type of a variable partway through a procedure in a dynamically typed language bad style?

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.

I’ll go out on a limb and say: No, this is a terrible idea.

It’s just a special case of reusing a variable, which is a bad idea – mainly because it makes it hard to understand what a variable contains at any given point in the program flow. See e.g. Should I reuse variables?

About your points: The points you raise are valid, it’s just that reusing the variable is not a good solution :-).

a) it conveys that the response variable contains basically the same
information, just ‘transformed’ into a different type

Providing this information is a good idea. However, don’t do this by using the same variable, because then you obscure the fact that it the information was transformed. Rather, use names with a common pre-/postfix. In your example:

rawResponse = urlopen(some_url)
[...]    
jsonResponse = response.read()
[...]    
responseData = json.loads(response)
[...]

This makes it clear that the variables are closely related, but also that they do not contain the same data.

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.

Again, communicating this “no longer needed” is good, but don’t do it by reusing the variable: The reuse assignement will usually be hard to see, so you only confuse the reader.

Rather, if a variable lives long after its last use, that is an indication the method/function is too long. Split the part with the short-lived variables into a sub-function; that makes the code easier to read, and limits the variable lifetime.

Note: I usually even go one step further than not reusing variables, and try to even only assign a value once (i.e. never change the value, make it immutable). This is an idea mainly from functional languages, but I found it can make code much clearer. Of course, in non-functional languages, you sometimes need to change a variable (obvious example being a loop variable), but once you start looking, you’ll see that in most cases a “fresh” variable makes for more readable and less bug-prone code.

I know that you are reading from a URL in your example, but if you tried the same thing with a file you would not be able to close the file because response is no longer pointing to the file, it is now holding a sting you retrieved from the file.

That is the big danger, you might forget what value it holds because it changes during the life of the program or module. It will be confusing for somebody reading your code because they will never know what value type it is holding.

These are the fun bugs try and squash.

In general, I’d say yes, it is bad style, but that there are cases when it’s necessary and useful to reuse a variable; I’d just recommend avoiding casual, lazy use of it.

The problem with your example isn’t because of dynamic typing, but because you use the same variable to refer to three different things. This code is less clear to me because when I read it, I have to think much harder to figure out what response refers to.

You could do something similarly nasty in a statically typed language such as Java (with the restriction that the different things are related through a type hierarchy). The key point is that using a single variable to point to different objects can be confusing, regardless of type system.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật