by rpcope1 · 11y ago · 0 comments
cache.add_message("Hey, your {zoop} is {boop}".format(zoop=zoop, boop=boop))
That that call to "format" just kind of sucks -- it repeats what's already pretty obvious by looking at the string. It's specially crappy when you have strings that need lots of variables. We've taken to doing this recently, which I'm usually okay with: cache.add_message("Hey, your {} is {}".format(zoop, boop))
The downside of that is you have to make sure that the order of the arguments matches exactly with the order of the empty brackets. It's kinda error prone... But generally not that big of a deal.We could also do this...
cache.add_message("Hey, your %s is %s" % zoop, boop))
Or this... cache.add_message("{1} alert! Hey, your {0} is {1}".format(zoop, boop))
So yeah, I would argue that string formatting in Python is ALREADY in a kinda nasty place. There's ALREADY a bunch of ways to do it, and it all just kinda sucks.IMO, Ruby-style string formatting is probably the nicest I've seen. If it were in Python, it absolutely would be THE way to do string formatting, I bet.
cache.add_message("Hey, your {zoop} is {boop}")
So much nicer. bar='batz'
"foo #{bar} #{0.5+0.5}"
=> "foo batz 1.0"
"foo %s %.2f" % [bar, 1.0]
=> "foo batz 1.00"I'm not the poster but IMHO it fixes Python's syntax which is a case of DRY violation.
EDIT: To me, seeing this is Python code anywhere would seem to violate principle of least astonishment, which I think is somewhat more important than being DRY, if that's even a problem here.
"Hello {person}, it's a {weather} day".format(person=person, weather=weather)
The list of variables (person, weather) shows up three times.Somewhat off-topic, a similar problem shows up when you have a bunch of related functions, all taking a particular kwarg (or kwargs), and calling each other. Like
def foo(arg, conf1=None, conf2=None):
bar(arg+2, conf1=conf1, conf2=conf2) # eww :(
def bar(arg, conf1=None, conf2=None):
# etc.
A neat thing that perl6 has is syntax for "keyword argument whose value is found in the variable of the same name". So the equivalent of that line could be written bar($arg+2, :conf1($conf1), :conf2($conf2))
but it could also be bar($arg+2, :$conf1, :$conf2)