In some cases calling operator.index(n) may yield the desired result. I like operator.index, but maybe it is just me :). That uses duck typing instead of instance checking to ask if it represents an integer. But it also has some awkward corner cases in numpy, since arrays with a single element (deprecation pending) and 0D arrays (will continue) say they are integers when asked that way.
- Sebastian On Mi, 2015-06-17 at 23:13 -0700, Nathaniel Smith wrote: > On Wed, Jun 17, 2015 at 10:53 PM, Jens Jørgen Mortensen > <je...@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 >
signature.asc
Description: This is a digitally signed message part
_______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion