Reputation: 181
How do I properly create type hints if the value isn't assigned yet.
For example:
class foo():
def __init__():
data: np.ndarray = None
def load_data():
data = np.loadtxt(...)
Now I obviously get a warning, that type ndarray is expected, and not None. What is an elegant solution to this? Do I just make up some ndarray like data: np.ndarray = np.array([])
? That seams just wrong to me, and I'm sure there is a better way of doing it.
I still prefer the None version, because if there is an error with reading the numpy array, I will get an error like "can't calculate ... with type None". Then I imideatly know, it didn't read the file. Whereas, if the array is just empty, I might get weird errors, I don't understand.
SOLUTION:
Thanks to the commentators, pointing this out. The solution is importing Optional from typing, and then use Optional[np.ndarray]
instead of np.ndarray
Upvotes: 2
Views: 935
Reputation: 156
Consider using data: np.ndarray = np.empty([])
Or if you know the dimension of the array, initialize it with its dimensions.
See numpy.empty for more information.
Good Luck,
Ben
Upvotes: 1