String changing size on failure?

Chris Angelico rosuav at gmail.com
Wed Nov 1 16:01:10 EDT 2017


On Thu, Nov 2, 2017 at 6:26 AM, Ned Batchelder <ned at nedbatchelder.com> wrote:
> From David Beazley (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
>
> Huh?

There are optional parts to the Python string object that don't get
memory allocated for them until they're used. Apparently calling
float() on a string triggers one of those allocations (possibly the
UTF-8 representation?). You'd have to mess around with ctypes to see
exactly what's going on.

ChrisA



More information about the Python-list mailing list