Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

python - How to determine if a number is any type of int (core or numpy, signed or not)?

I need to test whether a variable is of type int, or any of np.int*, np.uint*, preferably using a single condition (i.e. no or).

After some tests, I guess that:

  • isinstance(n, int) will only match int and np.int32 (or np.int64 depending on plateform),
  • np.issubdtype(type(n), int) seems to match all int and np.int*, but doesn’t match np.uint*.

This leads to two questions: will np.issubdtype match any kind of signed ints? Can determine in a single check whether a number is any kind of signed or unsigned int?

This is about testing for integers, the test should return False for float-likes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

NumPy provides base classes that you can/should use for subtype-checking, rather than the Python types.

Use np.integer to check for any instance of either signed or unsigned integers.

Use np.signedinteger and np.unsignedinteger to check for signed types or unsigned types.

>>> np.issubdtype(np.uint32, np.integer)
True
>>> np.issubdtype(np.uint32, np.signedinteger)
False
>>> np.issubdtype(int, np.integer)
True

All floating or complex number types will return False when tested.

np.issubdtype(np.uint*, int) will always be False because the Python int is a signed type.

A useful reference showing the relationship between all of these base classes is found in the documentation here.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...