forked from data-apis/array-api-compat
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_internal.py
59 lines (40 loc) · 1.38 KB
/
_internal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
Internal helpers
"""
fromcollections.abcimportCallable
fromfunctoolsimportwraps
frominspectimportsignature
fromtypesimportModuleType
fromtypingimportTypeVar
_T=TypeVar("_T")
defget_xp(xp: ModuleType) ->Callable[[Callable[..., _T]], Callable[..., _T]]:
"""
Decorator to automatically replace xp with the corresponding array module.
Use like
import numpy as np
@get_xp(np)
def func(x, /, xp, kwarg=None):
return xp.func(x, kwarg=kwarg)
Note that xp must be a keyword argument and come after all non-keyword
arguments.
"""
definner(f: Callable[..., _T], /) ->Callable[..., _T]:
@wraps(f)
defwrapped_f(*args: object, **kwargs: object) ->object:
returnf(*args, xp=xp, **kwargs)
sig=signature(f)
new_sig=sig.replace(
parameters=[parfori, parinsig.parameters.items() ifi!="xp"]
)
ifwrapped_f.__doc__isNone:
wrapped_f.__doc__=f"""\
Array API compatibility wrapper for {f.__name__}.
See the corresponding documentation in NumPy/CuPy and/or the array API
specification for more details.
"""
wrapped_f.__signature__=new_sig# pyright: ignore[reportAttributeAccessIssue]
returnwrapped_f# pyright: ignore[reportReturnType]
returninner
__all__= ["get_xp"]
def__dir__() ->list[str]:
return__all__