简体   繁体   中英

Same variable name for different types in Python

I find myself doing the equivalent of something like this a lot:

msg = ['This', 'is', 'a', 'message']  # (or built up programmatically)
msg = ' '.join(msg)

which changes the type of the variable msg from a list to a str , as is allowed for a dynamically-typed language like Python. Is it a good idea, though? There's not much confusion here where the assignments are close together, but what if msg were used in its two different guises in widely-spaced bits of code?

but what if msg were used in its two different guises in widely-spaced bits of code?

You've hit the nail on the head. Using the same reference name just adds one more thing for the programmer to keep note of when scanning the code - for this reason alone it's better to use a different name.

Personally I use something like:

msg = ['This', 'is', 'a', 'message']
msg_str = ' '.join(msg)

My suggestion is that you don in your code only what you actually intend to do, and nothing else. If you think about your example, what does it actually do?

The first line takes a value (specifically a list) and puts a label on it, because as Sylvain Leroux mentioned in the comment this is all a variable actually is. Then, in the second line you use that value to create another value (a string this time) and then -- this is the important part -- you take the label off of the first value and put it on the second.

Is this really what you wanted to do? Basically, the first value (the list) was a throwaway intermediate step to the final value that you really needed, and was discarded as its job was done. In this particular case, the code could have easily be written as:

msg = ' '.join(['This', 'is', 'a', 'message'])

On the other hand, if you actually need two different values, one based on the other, used independently elsewhere in the code, then by all means do create a different variable name, as suggested by martin Konecny.

The important thing here is to keep in mind that variables are actually labels applied to different values, and can be moved away from one value and assigned to another. In fact, it's quite standard to have a value 'labelled' with several different 'labels'; ie to assign a same value to multiple variables. The important bit here is the value, and not the variable, which is just a label in a namespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM