[Numpy-discussion] Python 3 and isinstance(np.int64(42), int)
Nathaniel Smith
njs at pobox.com
Thu Jun 18 02:13:39 EDT 2015
On Wed, Jun 17, 2015 at 10:53 PM, Jens Jørgen Mortensen
<jensj at fysik.dtu.dk> wrote:
> >>> type(n)
> <type 'numpy.int64'>
> >>> isinstance(n, int)
> True
>
> With Python 3.4 you get False. I think I understand why (np.int64 is no
> longer a subclass of int).
Yep, that's correct.
> So, I did this instead:
>
> import numbers
> isinstance(n, numbers.Integral)
>
> which works fine (with numpy-1.9). Is this the "correct" way or is
> there a better way to do it?
That's the correct way to check whether an arbitrary object is of some
integer-like-type, yes :-). There are alternatives, and there's some
argument that in Python, doing explicit type checks like this is
usually a sign that one is doing something awkward, but that's a more
general issue that it's hard to comment on here without more detail
about what exactly you're trying to accomplish.
> I would imagine that a lot of code will
> break because of this - so it would be nice if isinstance(n, int) could
> be made to work the same way in 2 and 3, but I don't know if this is
> possible (or desirable).
It's not possible, unfortunately. In py2, 'int' is a 32- or 64-bit
integer type, so we can arrange for numpy's int32 or int64 objects to
be laid out the same in memory, so everything in python that expects
an int (including C API functions) can handle a numpy int. In py3,
'int' is an arbitrary width integer bignum, like py2 'long', which is
fundamentally different from int32 and int64 in both semantics and
implementation.
-n
--
Nathaniel J. Smith -- http://vorpus.org
More information about the NumPy-Discussion
mailing list