views:

111

answers:

3

In Python 2.x, using backticks to get decimal string from int object is Horrible? Because backticks are repr(), not str()? I have noticed that when I answering this question.

In Python source, they have same function in Python source, intobject.c

(reprfunc)int_to_decimal_string,            /* tp_repr */
....
(reprfunc)int_to_decimal_string,            /* tp_str */

What do you think?

+5  A: 

Well, I wouldn't say it's "horrible", but I feel it isn't right for at least four reasons:

  1. str(my_number) states your intent more clearly than surrounding my_number by backticks. (See "Readability counts" in the Zen of Python).

  2. The implementation of Python in C is just one possible implementation; there is Jython, IronPython, PyPy and so on, and unless there is an explicit statement in the Python specification somewhere that repr() and str() is the same for integer objects, I wouldn't to rely on that behaviour.

  3. Backticks are gone in Python 3.x.

  4. If your number happens to be so large that it cannot be represented by an int, Python promotes it automatically to a long integer, and for that, repr() and str() differs.

See this example:

>>> x = 1234567890
>>> y = x ** 3
>>> `y`
'1881676371789154860897069000L'
>>> str(y)
'1881676371789154860897069000'
Tamás
+1, Well said! and thanks for the example.
S.Mark
To me another reason is that backticks probably come from the bash shell, so it probably doesn't make sense to people who don't know Unix.
Bastien Léonard
5. Constructs like repr(repr(x)) are confusing with the backquote syntax.
dan04
+2  A: 

Yes. Using backticks for anything is horrible.

You've got str(i), you've got '%d' % i, you've got .format(i); if you want the repr then say so directly with repr() or %r or whatever.

There was never a good reason to use backticks, they just made code less readable and much harder to parse. They are gone in Python 3.

bobince
+1 for the straight talking
S.Mark
A: 

2.X: Using backticks for anything is horrible. Use repr() or str() as required.

3.X: Backticks have vanished! Three cheers!!

John Machin