In Python 2.x, using backticks to get decimal string from int object is Horrible?
-
27-09-2019 - |
문제
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?
해결책
Well, I wouldn't say it's "horrible", but I feel it isn't right for at least four reasons:
str(my_number)
states your intent more clearly than surroundingmy_number
by backticks. (See "Readability counts" in the Zen of Python).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()
andstr()
is the same for integer objects, I wouldn't to rely on that behaviour.Backticks are gone in Python 3.x.
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()
andstr()
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!!