31

What is the significance of the underscore suffixing in int_, float_, etc.?

1
  • 1
    I would suppose it's so they don't clash with builtins. It's the same reason you wouldn't create your own class named list. Commented Jun 1, 2011 at 17:21

2 Answers 2

29

From page 21 of Guide to Numpy by TE Oliphant:

Names for the data types that would clash with standard Python object names are followed by a trailing underscore, ’ ’. These data types are so named because they use the same underlying precision as the corresponding Python data types.

. . .

The array types bool_, int_, complex_, float_, object_, unicode_, and str_ are enhanced-scalars. They are very similar to the standard Python types (without the trailing underscore) and inherit from them (except for bool_ and object_). They can be used in place of the standard Python types whenever desired. Whenever a data type is required, as an argument, the standard Python types are recognized as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Oliphant's book looks great. Thanks for posting it.
5

If you're unsure if your variable is scalar, list, or array, using the ones with "_" will ensure your code will work regardless (if that's the behavior you intended). See the example code below.

As of numpy version 1.20.0, np.float64 or np.float32 works on scalars and lists.

import numpy as np  # numpy >= 1.20.0
scalar = 3
L1 = [3]
L2 = [1, 2, 3]

np.float64(scalar)  # okay
np.float64(L1)  # okay
np.float64(L2)  # okay

np.float_(scalar)  # okay
np.float_(L1)  # okay
np.float_(L2)  # okay

Note that np.float_ is just an alias of np.double.

2 Comments

How does this change now that np.float is deprecated?
Updated the answer to reflect the changes. np.float is deprecated but np.float_ isn't, though the latter is just an alias of np.double

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.