[Numpy-discussion] floats coerced to string with "{:f}".format() ?

Robert Kern robert.kern at gmail.com
Thu Jun 6 16:26:13 EDT 2013

On Thu, Jun 6, 2013 at 9:18 PM, Maccarthy, Jonathan K <jkmacc at lanl.gov> wrote:
> Ah, so np.int64 and np.str inherit the native Python __format__(), but np.float32/64 doesn't get __builtin__.float.__format__().  That's not intuitive, but I see now why this works:
> In [8]: '{:6.6s} {:8d} {:11.6f}'.format(tmp.sta, tmp.ondate, float(tmp.lat))
> Out[8]: 'XYZZ    2001123  -23.820000'

np.float64 works because it inherits from the Python float type
(Python floats are 64-bit floats). np.float32 doesn't inherit from the
Python float type because it can't; they don't represent the same kind
of data, so their memory layouts at the C level cannot coincide. Since
you are on a 64-bit platform, np.int64 represents the same kind of
integer as the Python int type, so it can subclass, but an np.int32

It's not necessarily intuitive, but it's the best we can do under the
constraints. The only thing more intuitive would be to disallow
subclassing from the Python builtin types entirely, but that's
*really* annoying.

Robert Kern

More information about the NumPy-Discussion mailing list