Skip to content

Commit bd536d6

Browse files
committed
Allow Python scalars in array_namespace
They are just ignored. This makes array_namespace easier to use for functions that accept either arrays or scalars. I'm not sure if I should have this behavior by default, or if it should be enabled by a flag.
1 parent 7fa20da commit bd536d6

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

array_api_compat/common/_helpers.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,8 @@ def array_namespace(*xs, api_version=None, use_compat=None):
235235
Parameters
236236
----------
237237
xs: arrays
238-
one or more arrays.
238+
one or more arrays. xs can also be Python scalars (bool, int, float,
239+
or complex), which are ignored.
239240
240241
api_version: str
241242
The newest version of the spec that you need support for (currently
@@ -298,7 +299,9 @@ def your_function(x, y):
298299

299300
namespaces = set()
300301
for x in xs:
301-
if is_numpy_array(x):
302+
if isinstance(x, (bool, int, float, complex)):
303+
continue
304+
elif is_numpy_array(x):
302305
from .. import numpy as numpy_namespace
303306
import numpy as np
304307
if use_compat is True:

tests/test_array_namespace.py

+14
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,17 @@ def test_api_version():
9292
def test_get_namespace():
9393
# Backwards compatible wrapper
9494
assert array_api_compat.get_namespace is array_api_compat.array_namespace
95+
96+
def test_python_scalars():
97+
a = torch.asarray([1, 2])
98+
xp = import_("torch", wrapper=True)
99+
100+
pytest.raises(TypeError, lambda: array_namespace(1))
101+
pytest.raises(TypeError, lambda: array_namespace(1.0))
102+
pytest.raises(TypeError, lambda: array_namespace(1j))
103+
pytest.raises(TypeError, lambda: array_namespace(True))
104+
105+
assert array_namespace(a, 1) == xp
106+
assert array_namespace(a, 1.0) == xp
107+
assert array_namespace(a, 1j) == xp
108+
assert array_namespace(a, True) == xp

0 commit comments

Comments
 (0)