开发者

In Python 2.x, using backticks to get decimal string from int object is Horrible?

In Python 2.x, using backticks to get decimal string from int object is Horrible? Because backticks are repr(), not开发者_Python百科 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?


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'


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.


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜