Strings That Change Width

Contents
A megabyte of ASCII log text in Python 3.7 is a 1,000,049-byte object. Append one snake emoji to it and the result is 4,000,080 bytes, nearly four times as much memory for one more character, because every character in the new string, all million of them, is now stored in four bytes. That is not a quirk of a particular operation. It’s how CPython has stored strings since Python 3.3: each string picks the narrowest fixed width that fits its widest character, and one character is enough to widen all the others.
This post takes the str object apart: its header, read with ctypes as in Part 1, its three
widths, the second UTF-8 copy that C code can attach to it, the cached hash and why it changes from
run to run, the in-place += that only works while nothing else refers to the string, interning, and
the locale problem that Python 3.7 finally fixed.
This is Part 7 of a series on the CPython runtime. Part 1
read objects’ raw bytes, and Part 2 quoted the special case
in BINARY_ADD that this post explains. It is written for Python programmers who have written a
little C. Everything here ran on CPython 3.7.2, released on 24 December and built from its tag with
Ubuntu 18.04’s gcc 7.3.0, plus 18.04’s own Python 3.6.5 for one comparison. The note at the end says
exactly where and how.
Three widths
A Python string is a sequence of Unicode code points, from U+0000 to U+10FFFF. Storing every one in
four bytes, as UTF-32 does, makes indexing trivial and wastes three quarters of the memory for
ASCII text. Storing them as UTF-8 saves memory and makes s[i] a scan from the start. Python 3.3
adopted PEP 393, “Flexible String Representation”, which does neither: each string is stored as an
array of fixed-width units, and the width is chosen per string, at creation, as the narrowest of
three that fits its largest code point.
| Kind | Unit | Holds | In C |
|---|---|---|---|
| 1 | 1 byte | U+0000–U+00FF (Latin-1) | Py_UCS1 |
| 2 | 2 bytes | U+0000–U+FFFF (the Basic Multilingual Plane) | Py_UCS2 |
| 4 | 4 bytes | U+0000–U+10FFFF | Py_UCS4 |
The header that records the choice is PyASCIIObject, from Include/unicodeobject.h, cut to its
fields:
typedef struct {
PyObject_HEAD
Py_ssize_t length; /* Number of code points in the string */
Py_hash_t hash; /* Hash value; -1 if not set */
struct {
unsigned int interned:2;
unsigned int kind:3;
unsigned int compact:1;
unsigned int ascii:1;
unsigned int ready:1;
unsigned int :24;
} state;
wchar_t *wstr; /* wchar_t representation (null-terminated) */
} PyASCIIObject;
typedef struct {
PyASCIIObject _base;
Py_ssize_t utf8_length; /* Number of bytes in utf8, excluding the
* terminating \0. */
char *utf8; /* UTF-8 representation (null-terminated) */
Py_ssize_t wstr_length; /* Number of code points in wstr, possible
* surrogates count as two code points. */
} PyCompactUnicodeObject;
A pure-ASCII string uses the 48-byte PyASCIIObject header followed directly by its characters and
a NUL. Any other string uses the 72-byte PyCompactUnicodeObject, which adds room for a UTF-8 copy
(below). The state bit-field is four bytes at offset 32, and it can be decoded from Python:
import ctypes, struct, sys
def header(s):
"""Decode a str's PyASCIIObject header: length, hash and the state bit-field."""
raw = ctypes.string_at(id(s), 40)
length, hsh, state = struct.unpack_from("<qqI", raw, 16)
return {"length": length, "hash": hsh,
"interned": state & 3, "kind": (state >> 2) & 7, "compact": (state >> 5) & 1,
"ascii": (state >> 6) & 1, "ready": (state >> 7) & 1}
That’s saved as header.py and used by the rest of the scripts. Here is one string, widened one
character at a time:
import sys
from header import header
base = "a" * 1000
for label, s in [("1000 x 'a'", base),
("... + 'é' (U+00E9)", base + "é"),
("... + 'Ω' (U+03A9)", base + "Ω"),
("... + '🐍' (U+1F40D)", base + "\U0001F40D")]:
h = header(s)
print("%-22s len %4d getsizeof %4d kind %d ascii %d compact %d" %
(label, len(s), sys.getsizeof(s), h["kind"], h["ascii"], h["compact"]))
$ python3 kinds.py
1000 x 'a' len 1000 getsizeof 1049 kind 1 ascii 1 compact 1
... + 'é' (U+00E9) len 1001 getsizeof 1074 kind 1 ascii 0 compact 1
... + 'Ω' (U+03A9) len 1001 getsizeof 2076 kind 2 ascii 0 compact 1
... + '🐍' (U+1F40D) len 1001 getsizeof 4080 kind 4 ascii 0 compact 1
Every size follows from the header and the kind:
- 1,000 × ‘a’: 48 bytes of header, 1,000 one-byte characters, a NUL: 1,049.
- + ‘é’: still one byte each, since é is U+00E9, inside Latin-1. But
asciiis now 0, so the header is the 72-byte compact one: 72 + 1,001 + 1 = 1,074. - + ‘Ω’: U+03A9 is outside Latin-1, so every character takes two bytes: 72 + 2,002 + 2 = 2,076.
- + ‘🐍’: U+1F40D is outside the Basic Multilingual Plane, so every character takes four: 72 + 4,004 + 4 = 4,080.
The thousand as are the same characters in all four strings, at one, one, two and four bytes each.
How wide is your string?
Type anything. The size is the PEP 393 rule for a compact str on 64-bit CPython 3.7, checked below against four measured strings.
| measured in kinds.py | len | getsizeof | kind | rule gives |
|---|---|---|---|---|
| 1000 x 'a' | 1000 | 1049 | 1 B | 1049 ✓ |
| + 'é' (U+00E9) | 1001 | 1074 | 1 B | 1074 ✓ |
| + 'Ω' (U+03A9) | 1001 | 2076 | 2 B | 2076 ✓ |
| + '🐍' (U+1F40D) | 1001 | 4080 | 4 B | 4080 ✓ |
Each square under a character is one byte of storage. One character above U+00FF makes every character two bytes; one above U+FFFF makes every character four. JavaScript counts some characters differently from Python (it splits those above U+FFFF into two), so the calculator counts code points the way Python does.
The leak: one character, four times the memory
At the scale of real data:
import sys
log = "GET /index.html 200\n" * 50000 # a megabyte of ASCII
print("log: %8d bytes" % sys.getsizeof(log))
tagged = log + "\U0001F40D" # one more character
print("log + one '🐍': %8d bytes" % sys.getsizeof(tagged))
print("log[0] is the same character in both:", log[0] == tagged[0])
$ python3 emoji.py
log: 1000049 bytes
log + one '🐍': 4000080 bytes
log[0] is the same character in both: True
The concatenation had to allocate a new string of the widest kind and convert every one of the
million ASCII characters to a four-byte unit. A file read into memory, a JSON document, a template:
if any one of them contains an emoji or another character above U+FFFF, the whole string takes four
bytes per character, and any string built from it does too, until something slices the wide
character out. The language says nothing about this. len() is the same, indexing is the same, and
equality is the same. Only memory and copying time tell you which kind you have.
The trade is deliberate. Fixed width keeps s[i] and len(s) O(1) and makes slicing a copy of a
contiguous range, which UTF-8 can’t do. Most text is ASCII or Latin-1, which costs one byte per
character, the same as UTF-8, and needs no decoding to index. The price is paid only by strings that
mix narrow and wide characters, and then it’s paid in full.
A second copy, in UTF-8
C code often needs a string as UTF-8 bytes: to pass a file name to open(), a key to a database
library, text to a C parser. The C API’s PyUnicode_AsUTF8 returns a char * to it, and the caller
doesn’t own that buffer, so CPython has to keep it somewhere. It keeps it in the string itself, in the
utf8 field of the compact header, for as long as the string lives:
import ctypes, sys
as_utf8 = ctypes.pythonapi.PyUnicode_AsUTF8
as_utf8.restype = ctypes.c_char_p
as_utf8.argtypes = [ctypes.py_object]
s = "é" * 1000 # 1-byte kind, but not ASCII
print("before: ", sys.getsizeof(s))
s.encode("utf-8")
print("after s.encode('utf-8'): ", sys.getsizeof(s))
as_utf8(s) # what a C extension does to get a char *
print("after PyUnicode_AsUTF8(s): ", sys.getsizeof(s))
a = "a" * 1000
as_utf8(a)
print("ASCII string after the same:", sys.getsizeof(a), "(its data already is UTF-8)")
$ python3 utf8cache.py
before: 1073
after s.encode('utf-8'): 1073
after PyUnicode_AsUTF8(s): 3074
ASCII string after the same: 1049 (its data already is UTF-8)
s.encode() returns a new bytes object and leaves the string alone. But one call to
PyUnicode_AsUTF8, the call a C extension makes, attaches a 2,001-byte UTF-8 copy to the string
(é is two bytes in UTF-8), and the string’s size nearly triples, permanently. An ASCII string is
spared: its one-byte data already is valid UTF-8, so the pointer just points at it. Which library
calls do this is invisible from Python. Any C extension that takes str arguments might, and every
string it has seen carries the extra copy until it’s freed.
The hash that changes every run
The hash field caches the string’s hash: −1 until something asks, then the value forever. And that
value is different every time you start Python:
from header import header
s = "".join(["py", "thon"]) # built at run time, not a constant
print("hash field before:", header(s)["hash"])
print("hash(s) :", hash(s))
print("hash field after :", header(s)["hash"])
print("set order:", list({"red", "green", "blue", "cyan"}))
$ python3 hashes.py
hash field before: -1
hash(s) : -5426258494233063870
hash field after : -5426258494233063870
set order: ['red', 'blue', 'cyan', 'green']
$ python3 hashes.py
hash field before: -1
hash(s) : 7076607540158336349
hash field after : 7076607540158336349
set order: ['green', 'blue', 'cyan', 'red']
$ PYTHONHASHSEED=0 python3 hashes.py
hash field before: -1
hash(s) : 4862606447579313120
hash field after : 4862606447579313120
set order: ['blue', 'green', 'red', 'cyan']
$ PYTHONHASHSEED=0 python3 hashes.py
hash field before: -1
hash(s) : 4862606447579313120
hash field after : 4862606447579313120
set order: ['blue', 'green', 'red', 'cyan']
String hashing is keyed. At start-up CPython fills a secret from os.urandom and mixes it into every
str and bytes hash. Randomisation has been on by default since Python 3.3, and the hash function has
been SipHash-2-4 since 3.4 (PEP 456). Before that, an attacker who knew
the hash function could send a web server thousands of form fields whose names all collided, and
turn every dict insertion into a linear scan, the hash-flooding attacks published in 2011. The key
makes collisions unpredictable from outside.
The visible side effect is the last line of each run. A set’s iteration order follows the hash
values, so the same four strings come out in a different order in every process. A test that compares
list(some_set) with a fixed list passes some of the time. A program that writes a set of strings to
a file produces a different file each run. PYTHONHASHSEED=0 turns the key off and makes both
deterministic, and the last two runs agree.
+= that peeks ahead
Strings are immutable, so s += "x" must make a new string and copy s into it. In a loop that is
quadratic: the n-th step copies n characters. But CPython does something else, and it needs one
condition that is easy to break:
import time
def build(n):
s = ""
for _ in range(n):
s += "x"
return s
def build_aliased(n):
s = ""
for _ in range(n):
s += "x"
alias = s # a second reference: s can no longer be resized in place
return s
for n in (100000, 200000, 400000):
for f in (build, build_aliased):
t = time.perf_counter()
f(n)
print("%-14s n=%6d %7.3f s" % (f.__name__, n, time.perf_counter() - t))
$ python3 concat.py
build n=100000 0.002 s
build_aliased n=100000 0.095 s
build n=200000 0.004 s
build_aliased n=200000 0.526 s
build n=400000 0.008 s
build_aliased n=400000 3.064 s
Building a string with +=, with and without one more reference
CPython 3.7.2. Both axes are logarithmic: a line with slope 1 is linear time, slope 2 is quadratic.
s += "x"s += "x"; alias = sHover or focus a point for its time.
At 400,000 characters the aliased loop takes 383 times as long. Doubling n doubles the plain loop's time and multiplies the aliased loop's by more than four.
build is linear: twice the characters, twice the time. build_aliased, which only adds one more
variable pointing at the same string, is quadratic and 380 times slower at 400,000 characters. The
difference is in ceval.c, in the special case BINARY_ADD and INPLACE_ADD make for two strings,
which Part 2 quoted without explaining:
static PyObject *
unicode_concatenate(PyObject *v, PyObject *w,
PyFrameObject *f, const _Py_CODEUNIT *next_instr)
{
PyObject *res;
if (Py_REFCNT(v) == 2) {
/* In the common case, there are 2 references to the value
* stored in 'variable' when the += is performed: one on the
* value stack (in 'v') and one still stored in the
* 'variable'. We try to delete the variable now to reduce
* the refcnt to 1.
*/
int opcode, oparg;
NEXTOPARG();
switch (opcode) {
case STORE_FAST:
{
PyObject **fastlocals = f->f_localsplus;
if (GETLOCAL(oparg) == v)
SETLOCAL(oparg, NULL);
break;
}
...
}
}
res = v;
PyUnicode_Append(&res, w);
return res;
}
The interpreter reads the next instruction. If it’s a STORE_FAST into the variable that holds this
very string, as it is for s += "x", it clears the variable early, so that the only reference left is
the one on the value stack. Then PyUnicode_Append checks whether the string may be changed in place:
static int
unicode_modifiable(PyObject *unicode)
{
assert(_PyUnicode_CHECK(unicode));
if (Py_REFCNT(unicode) != 1)
return 0;
if (_PyUnicode_HASH(unicode) != -1)
return 0;
if (PyUnicode_CHECK_INTERNED(unicode))
return 0;
if (!PyUnicode_CheckExact(unicode))
return 0;
return 1;
}
If nothing else refers to the string, it reallocs the string to the new length and copies only the
new characters on the end. realloc can often grow a block in place, and when it can’t, the move is
amortised by the allocator, so the loop is linear. The string is immutable only in the sense that
nobody can tell it was changed: nobody else has a reference to it.
In build_aliased, alias holds a second reference, the count is 2 after the early clear, and every
+= allocates a new string and copies the whole thing. The same happens if the string’s hash was
computed (it was used as a dict key, even once), if it’s interned, if it’s a subclass of str, or if
the += isn’t followed by a store into the same simple name, such as self.s += "x" or
d[k] += "x". None of these change what the program means. Each turns a linear loop into a
quadratic one, which is why the advice is still "".join(parts), which doesn’t depend on an
optimisation the language never promised. Other implementations don’t have it at all.
Interning
Some strings are made unique: the compiler interns identifiers and identifier-like constants by
putting them in a global dict, and reusing the dict’s copy whenever the same string is needed again,
so that attribute and global lookups can compare pointers instead of characters. The interned bits
of the header record it:
import sys
from header import header
a = "hello_world" # looks like an identifier: interned by the compiler
b = "".join(["hello", "_world"]) # built at run time
c = "hello world" # has a space: a constant, but not interned
print("a is b:", a is b, " interned:", header(a)["interned"], header(b)["interned"], header(c)["interned"])
b = sys.intern(b)
print("after sys.intern(b): a is b:", a is b)
$ python3 interning.py
a is b: False interned: 1 0 0
after sys.intern(b): a is b: True
a is interned (state 1, SSTATE_INTERNED_MORTAL) because the compiler interns string constants
that look like identifiers. c, with a space in it, isn’t. The run-time string b has the same
characters as a, but it’s a different object until sys.intern swaps it for the interned one. This
is the string version of Part 1’s small-integer cache, and the same rule applies: is on strings
tells you about the compiler’s interning heuristic, not about the strings. Interning is also why the
+= above won’t resize an interned string in place. The intern dict relies on its strings never
changing.
The C locale, and what 3.7 changed
The last leak is at the boundary with the operating system. A Unix process’s locale tells C code how
to turn bytes into characters, and the default locale, C (also called POSIX), says the bytes are
ASCII. CPython 3.6 believed it. In a Docker container, a cron job or an SSH session with no LANG
set, Python 3 decided that file names, the terminal and every text file were ASCII:
$ LANG=C /usr/bin/python3.6 -c 'import sys, locale; print(sys.getfilesystemencoding(), sys.stdout.encoding, locale.getpreferredencoding()); print("caf\u00e9")'
ascii ANSI_X3.4-1968 ANSI_X3.4-1968
Traceback (most recent call last):
File "<string>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 3: ordinal not in range(128)
$ LANG=C python3 -c 'import sys, locale; print(sys.getfilesystemencoding(), sys.stdout.encoding, locale.getpreferredencoding(), sys.flags.utf8_mode); print("caf\u00e9")'
utf-8 utf-8 UTF-8 1
café
Python 3.6.5 (18.04’s own) printing the word “café” in the C locale fails with UnicodeEncodeError,
and every program that writes non-ASCII text in such an environment fails with it too. Python 3.7.2
prints it. 3.7 brought two changes for this. PEP 538 coerces the C locale: at start-up, if the locale
is C, the interpreter sets LC_CTYPE to C.UTF-8 (or a similar UTF-8 locale) before anything else
reads it. PEP 540 adds a UTF-8 mode, -X utf8 or PYTHONUTF8=1, that ignores the locale and uses
UTF-8 for everything, and turns it on automatically in the C locale. The 1 in the output is
sys.flags.utf8_mode, which the interpreter set by itself.
$ LANG=C PYTHONCOERCECLOCALE=0 python3 -c 'import sys, locale; print(sys.getfilesystemencoding(), sys.stdout.encoding, locale.getpreferredencoding(), sys.flags.utf8_mode); print("caf\u00e9")'
utf-8 utf-8 UTF-8 1
café
$ LANG=C PYTHONCOERCECLOCALE=0 python3 -X utf8 -c 'import sys, locale; print(sys.getfilesystemencoding(), sys.stdout.encoding, locale.getpreferredencoding(), sys.flags.utf8_mode); print("caf\u00e9")'
utf-8 utf-8 UTF-8 1
café
With locale coercion turned off, UTF-8 mode alone still gives UTF-8 everywhere. The encodings that decide whether a program can print its own output are not part of the language. They come from the C library’s locale, read when the interpreter starts, and 3.7 is the first version that treats the C locale as the mistake it usually is.
What we covered
- Since 3.3, a
strstores its characters in 1, 2 or 4 bytes each, chosen per string by the widest character. The header, 48 bytes for ASCII and 72 for anything else, records the kind, andctypescan read it. - One character above U+FFFF made a megabyte of ASCII log text a four-megabyte string. Fixed width keeps indexing O(1) and makes mixed strings pay in full.
PyUnicode_AsUTF8, the call C extensions make, attaches a UTF-8 copy to the string for its lifetime. A 1,073-byte string became 3,074 bytes.- String hashes are keyed with a random secret per process (SipHash since 3.4), cached in the header after first use, and change from run to run, and so does the iteration order of sets of strings.
s += tin a loop is linear only because the eval loop reads the next instruction, clears the variable early, and resizes the string in place when nothing else refers to it. One alias made it quadratic and 380 times slower.- The compiler interns identifier-like constants.
sys.interndoes it at run time, andison strings reports the heuristic. - In the C locale, 3.6 used ASCII for files and terminals and failed on “café”. 3.7 coerces the locale to UTF-8 (PEP 538) and turns on UTF-8 mode (PEP 540).
The next post opens the data structure that interning, globals, attributes and keyword arguments all rest on: the dict.
A note on the evidence
What I ran, and where. Everything ran on CPython 3.7.2, built from the v3.7.2 tag with Ubuntu
18.04’s gcc 7.3.0, on a minimal 18.04 userland from the release archive, as a chroot on a 64-bit x86
machine. The locale comparison also used 18.04’s own python3.6 3.6.5-3 from the same root. Nothing
here depends on the kernel. The scripts ran with LANG=C.UTF-8 except where the command sets LANG=C.
Each script was extracted from this page and run as shown.
The numbers. Sizes and header fields are deterministic for this build. The hashes are what four
consecutive runs printed. Any other runs print other values, except with PYTHONHASHSEED=0. The
concat.py timings are one run on an idle machine. Their ratios, linear against quadratic, are the
point.
What I worked out rather than read. The size arithmetic (48 and 72-byte headers) is from the
struct definitions and sizeof on this 64-bit build, checked against getsizeof. That the aliased
loop fails unicode_modifiable on its reference count, rather than on another condition, follows from
the code; I didn’t step through it in a debugger.
What I cited rather than ran. The C quoted here is from the v3.7.2 tag: Include/unicodeobject.h,
Objects/unicodeobject.c (unicode_modifiable, PyUnicode_Append) and Python/ceval.c
(unicode_concatenate). PEP 393 (3.3), PEP 456 (3.4), PEP 538 and PEP 540 (3.7) are cited from the
PEPs. The 2011 hash-flooding attacks are from the “Efficient Denial of Service Attacks on Web
Application Platforms” presentation at 28C3 (December 2011) and the python-dev discussion that
followed.
What I’d still change. I didn’t check which standard-library functions call PyUnicode_AsUTF8,
only that the C API call attaches the copy. A survey of the stdlib’s C modules would say how common
the doubled strings are in practice.
Strings That Change Width