1

I have legacy windows numpy code with a lot of nd.array intgers without explicit dtype. In windows they are treated as np.int32. Moving to linux, they become np.int64 which cause a lot of types problems.

Instead of adding explicit dtype on many places in the code,

Can I somehow force numpy on linux 64 to treat integers as np.int32 and not np.int64. For example: np.array(1) will become np.int32.

I saw it's been asked in 1, ~two years ago and wondering if maybe something had changed since then.

Lior Cohen
  • 5,570
  • 2
  • 14
  • 30

1 Answers1

1

One workaround for your legacy code could be a decorator for array constructors that turns objects of dtype int64 in to those of dtype int32:

from functools import wraps

def intas32(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        obj = func(*args, **kwargs)
        if (kwargs.get('dtype') is None 
            and hasattr(obj, 'dtype')
            and obj.dtype == np.int64):
            return obj.astype(np.int32)
        return obj
    return wrapper

Now create your one versions:

my_arange = intas32(np.arange)

and use it:

>>> my_arange(2)
array([0, 1], dtype=int32)

or monkey patch NumPy for all needed functions:

>>> np.arange = intas32(np.arange)
>>> np.arange(2)
array([0, 1], dtype=int32)
>>> np.array = intas32(np.array)
>>> np.array(1)
array(1, dtype=int32)

Be careful and test if this really works.

You can do this programmatically:

for name in ['array', 'arange']:
    obj = getattr(np, name)
    setattr(np, name, intas32(obj))
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • Thanks Mike. Very elegant but I am afraid it won't answer my needs as: 1. If someone do want int64 it still will cast to int32. 2. There are a lot of functions that I need to decorate. I guess there is no way to change the default of the simple python type casting – Lior Cohen Jan 31 '18 at 11:52
  • Fixed *If someone do want int64 it still will cast to int32* and added a loop for decorating all functions name in the list. – Mike Müller Jan 31 '18 at 12:27