0

suppose I want the default data type to be np.uint8, in such a way that when I call:

a = 2
print(type(a))

I get in output numpy.uint8.

Is it possible to obtain this?

Vincenzo Lavorini
  • 1,884
  • 2
  • 15
  • 26
  • 1
    What would be the objective of such a thing? – Dani Mesejo Feb 01 '19 at 12:25
  • 3
    If that *would* be possible, it wouldn't be Python anymore. – Klaus D. Feb 01 '19 at 12:27
  • @DanielMesejo : to write a routine that uses less memory, as example – Vincenzo Lavorini Feb 01 '19 at 12:31
  • @VincenzoLavorini If you need to optimize your code so much, that integers are using too much memory, then python is not the correct language to do it. – JE_Muc Feb 01 '19 at 12:33
  • You could do `a = np.uint(8)`, if that is too much, you could define an alias for the function, for example: `ui8 = np.uint8;a = ui8(2)`. – Dani Mesejo Feb 01 '19 at 12:40
  • we should remember that explicit is better than implicit, and what you are trying to do is an implicit conversion from Python's `int` to numpy's type – Azat Ibrakov Feb 01 '19 at 12:41
  • Don't confuse Python's own integer and float types with `numpy's` dtypes. `a=2` defines a Python integer. `type(a)` should not return a numpy type. `a = np.array([0,2,3], dtype='uint8')` creates an array with an explicit `dtype`. Your question should be whether `a.dtype` can be `uint8` by default or not. – hpaulj Feb 01 '19 at 17:43

1 Answers1

1

It's not possible, at least not with little effort, and it was discouraged when it was discussed on Numpy's issue tracker as 'unlikely to add', for good reason.

The easiest thing to do is to either use a function that takes the input and casts it to the desired data type or to check out this post on to 'overload' your numpy functions to always use eg. dtype=uint8.

hyperTrashPanda
  • 838
  • 5
  • 18