Skip to content

Commit efb0288

Browse files
authored
Merge pull request #7132 from njriasan/nick/astype_str_literals
gh #7131 Support for astype with literal strings
2 parents fd6a059 + 97a54df commit efb0288

3 files changed

Lines changed: 15 additions & 1 deletion

File tree

‎numba/core/typing/arraydecl.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
# import time side effect: array operations requires typing support of sequence
1010
# defined in collections: e.g. array.shape[i]
1111
from numba.core.typing import collections
12-
from numba.core.errors import TypingError
12+
from numba.core.errors import RequireLiteralValue, TypingError
1313

1414
Indexing = namedtuple("Indexing", ("index", "result", "advanced"))
1515

@@ -448,6 +448,9 @@ def resolve_astype(self, ary, args, kws):
448448
from .npydecl import parse_dtype
449449
assert not kws
450450
dtype, = args
451+
if isinstance(dtype, types.UnicodeType):
452+
raise RequireLiteralValue(("array.astype if dtype is a string it "
453+
"must be constant"))
451454
dtype = parse_dtype(dtype)
452455
if dtype is None:
453456
return

‎numba/np/arrayobj.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4303,6 +4303,7 @@ def array_ascontiguousarray(context, builder, sig, args):
43034303

43044304

43054305
@lower_builtin("array.astype", types.Array, types.DTypeSpec)
4306+
@lower_builtin("array.astype", types.Array, types.StringLiteral)
43064307
def array_astype(context, builder, sig, args):
43074308
arytype = sig.args[0]
43084309
ary = make_array(arytype)(context, builder, value=args[0])

‎numba/tests/test_array_methods.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,7 @@ def check(arr, dtype):
475475
check(arr, np.int32)
476476
check(arr, np.float32)
477477
check(arr, np.complex128)
478+
check(arr, "float32")
478479

479480
# F-contiguous
480481
arr = np.arange(24, dtype=np.int8).reshape((3, 8)).T
@@ -495,6 +496,15 @@ def check(arr, dtype):
495496
check(arr, dt)
496497
self.assertIn('cannot convert from int32 to Record',
497498
str(raises.exception))
499+
# Check non-Literal string raises
500+
unicode_val = "float32"
501+
with self.assertTypingError() as raises:
502+
@jit(nopython=True)
503+
def foo(dtype):
504+
np.array([1]).astype(dtype)
505+
foo(unicode_val)
506+
self.assertIn('array.astype if dtype is a string it must be constant',
507+
str(raises.exception))
498508

499509
def check_np_frombuffer(self, pyfunc):
500510
def run(buf):

0 commit comments

Comments
 (0)