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.

2
  • Can you link to the previous question? Commented Jan 31, 2018 at 10:18
  • Click on the 1. Commented Jan 31, 2018 at 10:19

1 Answer 1

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))
Sign up to request clarification or add additional context in comments.

2 Comments

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
Fixed If someone do want int64 it still will cast to int32 and added a loop for decorating all functions name in the list.

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.