On 23/10/2019 16:16, Steven D'Aprano wrote:
On Wed, Oct 23, 2019 at 03:16:51PM +0100, Rhodri James wrote:
I'm seriously not getting the issue people have with
colours1 = ["red", "green", "blue"]
which has the advantage of saying what it means.
As opposed to the alternatives, which say something different from what they mean?
["red", "green", "blue"]
says that this is a list of strings. End of.
"red green blue".split()
says that this is a string that is now -- ta dah! -- a list of strings. Nothing up my sleeves. No, don't clap, just throw money.
It's only a little bit of extra cognitive load in this case, but then you start meeting corner cases like wanting spaces in your strings and it stops being nearly so little.
%w[red green blue]
says that this is something, good luck figuring out what. If you know, it's only a little more cognitive load, but again gets messier as you get into the corner cases, as you've been demonstrating. If you don't know, looking it up is not going to be easy.
Wherever possible, we should let the interpreter or compiler do the repetitive stuff.
I prefer to let my editor do the work, actually. When I have had to do long lists of strings (or anything, really) like this, I mostly type it in as:
NOTIONAL_CONSTANT = [ red blue greeeeeen burnt umber burnt cake really long name with lots of spaces in it and so on and so on ]
and then write a quick editor macro to add the quotes and comma and tab into a more beautiful (and syntactically correct) form. Not much more trouble than typing it all in as an escaped string, and no extra runtime loading either. The result is immediately readable source, which I consider a major win.