Lior Cohen
Lior Cohen

Reputation: 5745

numpy default dtype for python integer

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.

Upvotes: 1

Views: 1217

Answers (1)

Mike Müller
Mike Müller

Reputation: 85442

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))

Upvotes: 1

Related Questions