This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Simplify converting non-ASCII strings to int, float and complex
Type: enhancement Stage: resolved
Components: Unicode Versions: Python 3.7
process
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: serhiy.storchaka Nosy List: ezio.melotti, serhiy.storchaka, vstinner
Priority: normal Keywords: patch

Created on 2017-11-08 12:21 by serhiy.storchaka, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Pull Requests
URL Status Linked Edit
PR 4336 merged serhiy.storchaka, 2017-11-08 12:24
PR 4527 merged vstinner, 2017-11-23 17:05
PR 8274 merged methane, 2018-07-13 13:12
Messages (6)
msg305824 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2017-11-08 12:21
This issue is inspired by the tweet https://twitter.com/dabeaz/status/925787482515533830

    >>> a = 'n'
    >>> b = 'ñ'
    >>> sys.getsizeof(a)
   50
    >>> sys.getsizeof(b)
   74
    >>> float(b)
   Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
   ValueError: could not convert string to float: 'ñ'
    >>> sys.getsizeof(b)
   77

See also a discussion on Python-list (https://mail.python.org/pipermail/python-list/2017-November/728149.html) and Stack Overflow (https://stackoverflow.com/questions/47062184/why-does-the-size-of-this-python-string-change-on-a-failed-int-conversion).


When convert a non-ASCII string which don't contain non-ASCII decimal digits and spaces, this will fail, but will change the size of the input string due to creating an internal UTF-8 representation.

This can look surprising for beginners, but there is nothing wrong here. There are many cases in which an internal UTF-8 representation is created implicitly.

But looking on the code I have found that it is too complicated. Parsers to int, float and complex call _PyUnicode_TransformDecimalAndSpaceToASCII() which transforms non-ASCII decimal digits and spaces to ASCII. This functions uses the general function fixup() which takes a transformation function, creates a new string object, apply the transformation. It checks if the transformation produces a string with larger maximal character code than the original string and creates a new string object and repeat the transformation in that case. Finally, if the resulting string is equal to the original string, destroy the resulting string and returns the original string. In the past fixup() was used for implementing methods like upper(). But now _PyUnicode_TransformDecimalAndSpaceToASCII() is only the user of fixup(), and it doesn't need all complicated logic of fixup(). For example, this transformation never produces wider strings.

The proposed PR simplifies the code by getting rid of fixup() and fix_decimal_and_space_to_ascii(). The semantic of _PyUnicode_TransformDecimalAndSpaceToASCII() has been changed. It now always produces ASCII string (this also simplifies caller places). If non-ASCII characters which is not a decimal digit and is not a space is encountered, the rest of the string is replaced with '?' which will cause an error in parsers.

The only visible behavior change (except not changing the size of the original string) is changing the exception raised by float() and complex() when the string contains lone surrogates from UnicodeEncodeError to ValueError (the same as for other malformed strings). int() already contained a special case for this and raised a ValueError.

Unpatched:

>>> int('\ud800')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '\ud800'
>>> float('\ud800')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'utf-8' codec can't encode character '\ud800' in position 0: surrogates not allowed
>>> complex('\ud800')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'utf-8' codec can't encode character '\ud800' in position 0: surrogates not allowed

Patched:

>>> int('\ud800')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '\ud800'
>>> float('\ud800')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '\ud800'
>>> complex('\ud800')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: complex() arg is a malformed string

This PR saves around 80 lines of code.
msg306163 - (view) Author: STINNER Victor (vstinner) * (Python committer) Date: 2017-11-13 17:09
I don't think that the weird behaviour justify to backport this non-trivial change. I propose to only apply the change in Python 3.7.
msg306166 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2017-11-13 19:22
As a side effect it slightly optimizes parsing non-ASCII numbers.

$ ./python -m perf timeit --compare-to=./python0  'int("۱۲۳۴۵۶۷۸۹")' --duplicate 100
python0: ..................... 277 ns +- 3 ns
python: ..................... 225 ns +- 3 ns

Mean +- std dev: [python0] 277 ns +- 3 ns -> [python] 225 ns +- 3 ns: 1.23x faster (-19%)

$ ./python -m perf timeit --compare-to=./python0  'float("۱۲۳۴۵.۶۷۸۹")' --duplicate 100
python0: ..................... 256 ns +- 1 ns
python: ..................... 199 ns +- 2 ns

Mean +- std dev: [python0] 256 ns +- 1 ns -> [python] 199 ns +- 2 ns: 1.29x faster (-22%)

$ ./python -m perf timeit --compare-to=./python0  'complex("۱۲۳۴۵.۶۷۸۹j")' --duplicate 100
python0: ..................... 298 ns +- 4 ns
python: ..................... 235 ns +- 3 ns

Mean +- std dev: [python0] 298 ns +- 4 ns -> [python] 235 ns +- 3 ns: 1.27x faster (-21%)
msg306167 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2017-11-13 19:23
New changeset 9b6c60cbce4ac45e8ccd7934babff465e9769509 by Serhiy Storchaka in branch 'master':
bpo-31979: Simplify transforming decimals to ASCII (#4336)
https://github.com/python/cpython/commit/9b6c60cbce4ac45e8ccd7934babff465e9769509
msg306168 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2017-11-13 19:26
Thank you for your review Victor.
msg306852 - (view) Author: STINNER Victor (vstinner) * (Python committer) Date: 2017-11-23 18:02
New changeset 6a54c676e63517653d3d4a1e164bdd0fd45132d8 by Victor Stinner in branch 'master':
bpo-31979: Remove unused align_maxchar() function (#4527)
https://github.com/python/cpython/commit/6a54c676e63517653d3d4a1e164bdd0fd45132d8
History
Date User Action Args
2022-04-11 14:58:54adminsetgithub: 76160
2018-07-13 13:12:17methanesetpull_requests: + pull_request7810
2017-11-23 18:02:25vstinnersetmessages: + msg306852
2017-11-23 17:05:56vstinnersetpull_requests: + pull_request4463
2017-11-13 19:26:01serhiy.storchakasetmessages: + msg306168
2017-11-13 19:25:21serhiy.storchakasetstatus: open -> closed
resolution: fixed
stage: patch review -> resolved
2017-11-13 19:23:52serhiy.storchakasetmessages: + msg306167
2017-11-13 19:22:00serhiy.storchakasetmessages: + msg306166
2017-11-13 17:09:42vstinnersetmessages: + msg306163
2017-11-08 12:24:15serhiy.storchakasetkeywords: + patch
stage: patch review
pull_requests: + pull_request4290
2017-11-08 12:21:21serhiy.storchakacreate