Implementation ported from CPython.