3 ms·
Yes, very nice, helpful site. .format() is mostly too verbose for my tastes. Even Guido himself put it into the "meh" category in a talk. To be clear, I do u
by mixmastamyk 12y ago
Yes, very nice, helpful site.
.format() is mostly too verbose for my tastes. Even Guido himself put it into the "meh" category in a talk. To be clear, I do use it when I need quick lightweight templating, say building a very complicated string.
But for most simple output printf style is shorter, simpler and I know it by heart. There was a guy at work who insisted on using .format() for everything that soured me on it, sometimes even simple string concatenation:
print 'result: {long_var_name}'.format({long_var_name=long_var_name})
Sometimes lines reached 200 chars. If lines were broken down, they might extend to 4 lines for each debug statement, adding tons of clutter. Said it was more readable because you could ignore the end. :/
As sago said, printf is more concise in the majority of use cases. Not to mention the logging niceties:
log.info('result: %s %s', one, two) # shorter and note that fmt is deferred!
A _big_ one in my eyes. Too bad logging doesn't support {} internally.
I've also wondered if .format could be improved if the % operator could be used with it, given appropriate precedence rules. Or perhaps use another char... dunno & or /?
print 'results: {} {}' % results
print 'results: {} {}' %% results
print 'results: {} {}' / results
Pycon, are you listening? ;)
- dalke 12y agoThis is what your co-worker does now: 'result: {long_var_name}'.format(long_var_name=long_var_name) A similar option is possible with '%'-style formatting: 'result: %(long_var_name)s'%{"long_var_name":long_var_name} -or- 'result: %(long_var_name)s'%dict(long_var_name=long_var_name) The first of these alternatives is indeed shorter, so long as there's only a single parameter. If there are multiple parameters then the .format() solution will be shorter. My experience with '%(name)s' % dict formatting is that I would often forget the terminal 's', and write it as '%(name)'. For template-like strings, where I want named substitutions, I am very much in favor of {}-style formatting. So if your co-worker insists on named substitutions, then s.format() is less verbose than s % dict. Regarding logging, there's a section of how to use format templates in the logging system, at https://docs.python.org/3/howto/logging-cookbook.html#formatting-styles https://docs.python.org/3/howto/logging-cookbook.html#format... . In addition to using a LogRecord factory, you could reduce the overhead in old-style logging to only an extra constructor calls: log.info(M('result: {} {}', one, two)) where M.__str__ forwards to str.format. Personally, I would like a way to pre-compile the format string: fmt = format_compile("result: {} {} {}") for result in results: print(fmt(*result)) because currently (in Python 3.3) "%d %d %d" is about 40% faster than "{} {} {}". EDIT: Never mind: It can be faster to interpolate the string each time than to call a constructor: % python3.3 -mtimeit 's="%s %s %s"' 's % (1, 3, 9)' 1000000 loops, best of 3: 0.36 usec per loop % python3.3 -mtimeit 'class Spam:pass' 'Spam()' 10000 loops, best of 3: 23.6 usec per loop I did not expect a factor of 65!
- zwegner 12y agoYour timeit calls in the edit need the -s parameter before the first statements, so they aren't executed on each loop iteration. The overhead is in creating the class, not the instances. $ python3 -mtimeit -s 's="%s %s %s"' 's % (1, 3, 9)' 1000000 loops, best of 3: 0.343 usec per loop $ python3 -mtimeit -s 'class Spam:pass' 'Spam()' 10000000 loops, best of 3: 0.106 usec per loop
- dalke 12y agoThanks! That's a big forehead smack on my side. The numbers are more in line with what I expected. Meaning it is possible to defer some of the time cost by using a single constructor rather than evaluating the string.
- mixmastamyk 12y agoI don't like all that verbosity in short debug text at all, no matter which syntax is used. I would have done, e.g.: print 'result:', long_var_name I do like your idea of a custom formatter though, perhaps it could be installed as a formatter into the logger beforehand, getting the slightly improved syntax without frequent object creation.
- dalke 12y agoRight, but the verbosity here is primarily due to your co-worker, given that the guy at your work would likely have used %(name)s instead of {name}. Regarding logging, the docs suggest that setting your own LogRecord factory is the way to go if that's what you want.
- mixmastamyk 12y agoStill, with % you can skip the .format() and while logging you can even skip the %. If {} was more "built-in" with an operator/logging I think it'd be a clearer win.
- 12y ago
- a3n 12y agoI use format because you can break lines within the parentheses. You also get to name parameters, which is nice and explicit. I also import print_function from the future, mainly because you can break lines inside the parentheses. I also use ' '.join([...]) for the same reason when building a large-ish string, you can break lines inside parentheses (or square brackets in this case). I like breaking lines inside parentheses and other delimiters.
- mixmastamyk 12y agoShould be able to do both of those with % as well: print '%(foo)s %(bar)s' % dict( foo='foo', bar='bar', )
- a3n 12y agohuh. I like it when I learn something new every day.