10 PEP 331: Locale-Independent Float/String Conversions

Python PEP

10 PEP 331: Locale-Independent Float/String Conversions

The locale modules lets Python software select various conversions and display conventions that are localized to a particular country or language. However, the module was careful to not change the numeric locale because various functions in Python's implementation required that the numeric locale remain set to the 'C' locale. Often this was because the code was using the C library's atof() function.

Not setting the numeric locale caused trouble for extensions that used third-party C libraries, however, because they wouldn't have the correct locale set. The motivating example was GTK+, whose user interface widgets weren't displaying numbers in the current locale.

The solution described in the PEP is to add three new functions to the Python API that perform ASCII-only conversions, ignoring the locale setting:

  • PyOS_ascii_strtod(str, ptr) and PyOS_ascii_atof(str, ptr) both convert a string to a C double.
  • PyOS_ascii_formatd(buffer, buf_len, format, d) converts a double to an ASCII string.

The code for these functions came from the GLib library (http://developer.gnome.org/arch/gtk/glib.html), whose developers kindly relicensed the relevant functions and donated them to the Python Software Foundation. The locale module can now change the numeric locale, letting extensions such as GTK+ produce the correct results.

See Also:

Written by Christian R. Reis, and implemented by Gustavo Carneiro.

See About this document... for information on suggesting changes.