News for hackers. Stuff that matters.
Re:Improving your (Python) code with modern idioms by andrewaylett on Tuesday May 08, 2012 @04:46AM (#3942792)
Python supports `"%(name)s"`, which means you're not dependent on order at all -- in my opinion, much nicer than indexing into the parameter list:

  >>> "%(name)s has %(count)d %(thing)s" % {'thing': 'bananas', 'count': 10, 'name': "Phil"}
  'Phil has 10 bananas'
Re:Improving your (Python) code with modern idioms by andolanra on Tuesday May 08, 2012 @07:12AM (#3943085)
The new-style formatting allows that as well:

    >>> "{name} has {count} {thing}".format(
          thing='bananas', count=10, name='Phil')
    'Phil has 10 bananas'
It also allows for more complex expressions inside of format specifiers, so if you need to grab data out of an object, you can do something like:

    >>> from collections import namedtuple
    >>> Sentence = namedtuple('Sentence', ['name', 'thing', 'count'])
    >>> s = Sentence(name='Phil', thing='bananas', count=10)
    >>> '{dat[0]} has {dat.count} {dat.thing}'.format(dat=s)
    'Phil has 10 bananas'
which is verbose and contrived here, but could be immensely useful in cases like

    >>> '... {numeral[5]} {item.plural}'.format(
          numeral=fr_numerals, item=animal)
    '... cinq animaux'
Re:Improving your (Python) code with modern idioms by 286c8cb04bda on Tuesday May 08, 2012 @10:38AM (#3943814)
How do you handle it when you need to convert, e.g., "American woman" to "femme américaine"?
Re:Improving your (Python) code with modern idioms by andolanra on Tuesday May 08, 2012 @12:26PM (#3944418)
You use something else. It's still just a format string, not a whole localization solution. Named arguments means it might be easier to hack together something like

    templates = {'en': '{adj} {noun}', 'fr': '{noun} {adj}'}
    print(templates['fr'].format(noun='fromage', adj='délicieux')
but that's still a hack, and doesn't even come close to addressing cases like Chinese's "{adj} {counter_word[noun]} {noun}" or gender concord or any of the myriad other things you come across in practice.

Edit: used 'positional' instead of 'named'.

Re:Improving your (Python) code with modern idioms by dalke on Tuesday May 08, 2012 @06:11AM (#3942969)
I found that I often (~1 time in 10) make a mistake with that syntax, and omit the trailing 's'. I think it's because I'm not used to having anything after a closing ')'.
Re:Improving your (Python) code with modern idioms by mturmon on Tuesday May 08, 2012 @03:09PM (#3945335)
Same problem here. Maybe the braces approach using {name} is an improvement upon %(name)s in that respect.