3 ms·
> There is a case when this will behave different from the original - if var is a tuple of one element. Hmm. I have a long habit of (almost) always using a one
by eesmith 6y ago
> There is a case when this will behave different from the original - if var is a tuple of one element.
Hmm. I have a long habit of (almost) always using a one-element tuple. Consider:
"foo %s" % x
The % operator on strings has a special case for tuples:
>>> x = "bar"
>>> "foo %s" % x
'foo bar'
>>> x = ("bar",)
>>> "foo %s" % x
'foo bar'
If you really want str(x) and are unsure that x might be a tuple, then you must use the tuple form:
>>> "foo %s" % (x,)
"foo ('bar',)"
or for a more involved example:
>>> from collections import namedtuple
>>> x=namedtuple("Foo", "foo")("bar")
>>> "foo %s" % x
'foo bar'
>>> "foo %s" % (x,)
"foo Foo(foo='bar')"
This might occur with input validation, like:
if isinstance(x, int):
return f_int(x)
elif isinstance(x, float):
return f_float(x)
else:
raise ValueError("Unsupported value: %s" % (x,))
In my code base there are at least 347 occurrences of this form:
% cat *.py */*.py | egrep -c '% \([a-zA-Z0-9_]+,\)'
347