Debian Codegraph @

pint/facets/numpy/unit.py

raw
1 """
2 pint.facets.numpy.unit
3 ~~~~~~~~~~~~~~~~~~~~~~
4
5 :copyright: 2022 by Pint Authors, see AUTHORS for more details.
6 :license: BSD, see LICENSE for more details.
7 """
8
9 from __future__ import annotations
10
11 from ...compat import is_upcast_type
12 from ..plain import PlainUnit
13
14
15 class NumpyUnit(PlainUnit):
16 __array_priority__ = 17
17
18 def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
19 if method != "__call__":
20 # Only handle ufuncs as callables
21 return NotImplemented
22
23 # Check types and return NotImplemented when upcast type encountered
24 types = {
25 type(arg)
26 for arg in list(inputs) + list(kwargs.values())
27 if hasattr(arg, "__array_ufunc__")
28 }
29 if any(is_upcast_type(other) for other in types):
30 return NotImplemented
31
32 # Act on limited implementations by conversion to multiplicative identity
33 # Quantity
34 if ufunc.__name__ in ("true_divide", "divide", "floor_divide", "multiply"):
35 return ufunc(
36 *tuple(
37 self._REGISTRY.Quantity(1, self._units) if arg is self else arg
38 for arg in inputs
39 ),
40 **kwargs,
41 )
42
43 return NotImplemented