Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow Python scalars in array_namespace #147

Merged
merged 2 commits into from
Nov 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions array_api_compat/common/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,8 @@ def array_namespace(*xs, api_version=None, use_compat=None):
Parameters
----------
xs: arrays
one or more arrays.
one or more arrays. xs can also be Python scalars (bool, int, float,
complex, or None), which are ignored.

api_version: str
The newest version of the spec that you need support for (currently
Expand Down Expand Up @@ -298,7 +299,9 @@ def your_function(x, y):

namespaces = set()
for x in xs:
if is_numpy_array(x):
if isinstance(x, (bool, int, float, complex, type(None))):
continue
elif is_numpy_array(x):
from .. import numpy as numpy_namespace
import numpy as np
if use_compat is True:
Expand Down
16 changes: 16 additions & 0 deletions tests/test_array_namespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,19 @@ def test_api_version():
def test_get_namespace():
# Backwards compatible wrapper
assert array_api_compat.get_namespace is array_api_compat.array_namespace

def test_python_scalars():
a = torch.asarray([1, 2])
xp = import_("torch", wrapper=True)

pytest.raises(TypeError, lambda: array_namespace(1))
pytest.raises(TypeError, lambda: array_namespace(1.0))
pytest.raises(TypeError, lambda: array_namespace(1j))
pytest.raises(TypeError, lambda: array_namespace(True))
pytest.raises(TypeError, lambda: array_namespace(None))

assert array_namespace(a, 1) == xp
assert array_namespace(a, 1.0) == xp
assert array_namespace(a, 1j) == xp
assert array_namespace(a, True) == xp
assert array_namespace(a, None) == xp
Loading