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

fix: lib for typetracers #558

Merged
merged 3 commits into from
Jan 22, 2025
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
2 changes: 1 addition & 1 deletion src/vector/_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -4400,7 +4400,7 @@ def _lib_of(*objects: VectorProtocol) -> Module: # NumPy-like module
if isinstance(obj, Vector):
if lib is None:
lib = obj.lib
elif lib is not obj.lib:
elif lib != obj.lib:
raise TypeError(
f"cannot use {lib} and {obj.lib} in the same calculation"
)
Expand Down
30 changes: 29 additions & 1 deletion src/vector/backends/awkward.py
Original file line number Diff line number Diff line change
Expand Up @@ -622,10 +622,38 @@ class AwkwardProtocol(Protocol):
def __getitem__(self, where: typing.Any) -> float | ak.Array | ak.Record | None: ...


class _lib(typing.NamedTuple):
"""a wrapper that respects the numpy-like interface of awkward-array and the module interface of numpy"""

module: types.ModuleType
nplike: ak._nplikes.numpy_like.NumpyLike

def __eq__(self, other: typing.Any) -> bool:
if isinstance(other, _lib):
return self.module is other.module and self.nplike is other.nplike
else:
return self.module is other

def __ne__(self, other: typing.Any) -> bool:
return not self.__eq__(other)

def __getattr__(self, name: str) -> typing.Any:
if fun := getattr(self.nplike, name, False):
return fun
else:
return getattr(self.module, name)


class VectorAwkward:
"""Mixin class for Awkward vectors."""

lib: types.ModuleType = numpy
@property
def lib(self): # type:ignore[no-untyped-def]
if (
nplike := self.layout.backend.nplike # type:ignore[attr-defined]
) is ak._nplikes.typetracer.TypeTracer.instance():
return _lib(module=numpy, nplike=nplike)
return numpy

def _wrap_result(
self: AwkwardProtocol,
Expand Down
Loading
Loading