3

I am currently doing some work where cupy is involved. Overall, it makes my code run faster, since it is running everything on my GPU. Now, if a user does not have cupy installed, but he does have numpy, I would like to make the necessary adjustment. Currently, I am importing them like: import numpy as np; import cupy as cp. I can make the check discussed here to test if cupy is not installed, so that's not a problem. But I wouldn't like to put conditionals everywhere or change cp to np, since that would complicate things if cupy is indeed installed and I'd like to use that instead. So, I tested out the following (which in theory would solve my issue):

import numpy as np
import numpy as cp

a = np.zeros((3, 3))
b = cp.zeros((3, 3))

>>> print(type(a))
    <class 'numpy.ndarray'>
>>> print(type(b))
    <class 'numpy.ndarray'>

And it seems to work. Nevertheless, I found this discussion (or this one) where people pointed out that multiple aliases for an import was a bad idea, but I didn't find any elaboration on why that was the case.

Could someone elaborate on this topic and illustrate how to go about this when dealing with the use of a module (cupy) whose alias, if not installed, should point to another one (numpy)?

Camilo Martinez M.
  • 1,420
  • 1
  • 7
  • 21

1 Answers1

2

To have another alias for a numpy import, why not just assign it?

import numpy as np
cp = np

# then just use it normally,
x = cp.arange(10)
tom10
  • 67,082
  • 10
  • 127
  • 137