How to write fast into a file in python?

Chris Angelico rosuav at gmail.com
Sat May 18 01:28:08 EDT 2013


On Sat, May 18, 2013 at 2:01 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Consider if x is an arbitrary object, and you call "%s" % x:
>
> py> "%s" % 23  # works
> '23'
> py> "%s" % [23, 42]  # works
> '[23, 42]'
>
> and so on for *almost* any object. But if x is a tuple, strange things
> happen

Which can be guarded against by wrapping it up in a tuple. All you're
seeing is that the shortcut notation for a single parameter can't
handle tuples.

>>> def show(x):
	return "%s" % (x,)

>>> show(23)
'23'
>>> show((23,))
'(23,)'
>>> show([23,42])
'[23, 42]'

One of the biggest differences between %-formatting and str.format is
that one is an operator and the other a method. The operator is always
going to be faster, but the method can give more flexibility (not that
I've ever needed or wanted to override anything).

>>> def show_format(x):
	return "{}".format(x) # Same thing using str.format
>>> dis.dis(show)
  2           0 LOAD_CONST               1 ('%s')
              3 LOAD_FAST                0 (x)
              6 BUILD_TUPLE              1
              9 BINARY_MODULO
             10 RETURN_VALUE
>>> dis.dis(show_format)
  2           0 LOAD_CONST               1 ('{}')
              3 LOAD_ATTR                0 (format)
              6 LOAD_FAST                0 (x)
              9 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             12 RETURN_VALUE

Attribute lookup and function call versus binary operator. Potentially
a lot of flexibility, versus basically hard-coded functionality. But
has anyone ever actually made use of it?

str.format does have some cleaner features, like naming of parameters:

>>> "{foo} vs {bar}".format(foo=1,bar=2)
'1 vs 2'
>>> "%(foo)s vs %(bar)s"%{'foo':1,'bar':2}
'1 vs 2'

Extremely handy when you're working with hugely complex format
strings, and the syntax feels a bit clunky in % (also, it's not
portable to other languages, which is one of %-formatting's biggest
features). Not a huge deal, but if you're doing a lot with that, it
might be a deciding vote.

ChrisA



More information about the Python-list mailing list