| 1 |
""" |
| 2 |
pint.facets.plain.unit |
| 3 |
~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
:copyright: 2016 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 |
import copy |
| 12 |
import locale |
| 13 |
import operator |
| 14 |
from numbers import Number |
| 15 |
from typing import TYPE_CHECKING, Any |
| 16 |
|
| 17 |
from ..._typing import UnitLike |
| 18 |
from ...compat import NUMERIC_TYPES, deprecated |
| 19 |
from ...errors import DimensionalityError |
| 20 |
from ...util import PrettyIPython, SharedRegistryObject, UnitsContainer |
| 21 |
from .definitions import UnitDefinition |
| 22 |
|
| 23 |
if TYPE_CHECKING: |
| 24 |
from ..context import Context |
| 25 |
|
| 26 |
|
| 27 |
class PlainUnit(PrettyIPython, SharedRegistryObject): |
| 28 |
"""Implements a class to describe a unit supporting math operations.""" |
| 29 |
|
| 30 |
def __reduce__(self): |
| 31 |
# See notes in Quantity.__reduce__ |
| 32 |
from pint import _unpickle_unit |
| 33 |
|
| 34 |
return _unpickle_unit, (PlainUnit, self._units) |
| 35 |
|
| 36 |
def __init__(self, units: UnitLike) -> None: |
| 37 |
super().__init__() |
| 38 |
if isinstance(units, (UnitsContainer, UnitDefinition)): |
| 39 |
self._units = units |
| 40 |
elif isinstance(units, str): |
| 41 |
self._units = self._REGISTRY.parse_units(units)._units |
| 42 |
elif isinstance(units, PlainUnit): |
| 43 |
self._units = units._units |
| 44 |
else: |
| 45 |
raise TypeError( |
| 46 |
"units must be of type str, Unit or UnitsContainer; not {}.".format( |
| 47 |
type(units) |
| 48 |
) |
| 49 |
) |
| 50 |
|
| 51 |
def __copy__(self) -> PlainUnit: |
| 52 |
ret = self.__class__(self._units) |
| 53 |
return ret |
| 54 |
|
| 55 |
def __deepcopy__(self, memo) -> PlainUnit: |
| 56 |
ret = self.__class__(copy.deepcopy(self._units, memo)) |
| 57 |
return ret |
| 58 |
|
| 59 |
@deprecated( |
| 60 |
"This function will be removed in future versions of pint.\n" |
| 61 |
"Use ureg.formatter.format_unit_babel" |
| 62 |
) |
| 63 |
def format_babel(self, spec: str = "", **kwspec: Any) -> str: |
| 64 |
return self._REGISTRY.formatter.format_unit_babel(self, spec, **kwspec) |
| 65 |
|
| 66 |
def __format__(self, spec: str) -> str: |
| 67 |
return self._REGISTRY.formatter.format_unit(self, spec) |
| 68 |
|
| 69 |
def __str__(self) -> str: |
| 70 |
return self._REGISTRY.formatter.format_unit(self) |
| 71 |
|
| 72 |
def __bytes__(self) -> bytes: |
| 73 |
return str(self).encode(locale.getpreferredencoding()) |
| 74 |
|
| 75 |
def __repr__(self) -> str: |
| 76 |
return f"<Unit('{self._units}')>" |
| 77 |
|
| 78 |
@property |
| 79 |
def dimensionless(self) -> bool: |
| 80 |
"""Return True if the PlainUnit is dimensionless; False otherwise.""" |
| 81 |
return not bool(self.dimensionality) |
| 82 |
|
| 83 |
@property |
| 84 |
def dimensionality(self) -> UnitsContainer: |
| 85 |
""" |
| 86 |
Returns |
| 87 |
------- |
| 88 |
dict |
| 89 |
Dimensionality of the PlainUnit, e.g. ``{length: 1, time: -1}`` |
| 90 |
""" |
| 91 |
try: |
| 92 |
return self._dimensionality |
| 93 |
except AttributeError: |
| 94 |
dim = self._REGISTRY._get_dimensionality(self._units) |
| 95 |
self._dimensionality = dim |
| 96 |
|
| 97 |
return self._dimensionality |
| 98 |
|
| 99 |
def compatible_units(self, *contexts): |
| 100 |
if contexts: |
| 101 |
with self._REGISTRY.context(*contexts): |
| 102 |
return self._REGISTRY.get_compatible_units(self) |
| 103 |
|
| 104 |
return self._REGISTRY.get_compatible_units(self) |
| 105 |
|
| 106 |
def is_compatible_with( |
| 107 |
self, other: Any, *contexts: str | Context, **ctx_kwargs: Any |
| 108 |
) -> bool: |
| 109 |
"""check if the other object is compatible |
| 110 |
|
| 111 |
Parameters |
| 112 |
---------- |
| 113 |
other |
| 114 |
The object to check. Treated as dimensionless if not a |
| 115 |
Quantity, PlainUnit or str. |
| 116 |
*contexts : str or pint.Context |
| 117 |
Contexts to use in the transformation. |
| 118 |
**ctx_kwargs : |
| 119 |
Values for the Context/s |
| 120 |
|
| 121 |
Returns |
| 122 |
------- |
| 123 |
bool |
| 124 |
""" |
| 125 |
from .quantity import PlainQuantity |
| 126 |
|
| 127 |
if contexts or self._REGISTRY._active_ctx: |
| 128 |
try: |
| 129 |
(1 * self).to(other, *contexts, **ctx_kwargs) |
| 130 |
return True |
| 131 |
except DimensionalityError: |
| 132 |
return False |
| 133 |
|
| 134 |
if isinstance(other, (PlainQuantity, PlainUnit)): |
| 135 |
return self.dimensionality == other.dimensionality |
| 136 |
|
| 137 |
if isinstance(other, str): |
| 138 |
return ( |
| 139 |
self.dimensionality == self._REGISTRY.parse_units(other).dimensionality |
| 140 |
) |
| 141 |
|
| 142 |
return self.dimensionless |
| 143 |
|
| 144 |
def __mul__(self, other): |
| 145 |
if self._check(other): |
| 146 |
if isinstance(other, self.__class__): |
| 147 |
return self.__class__(self._units * other._units) |
| 148 |
else: |
| 149 |
qself = self._REGISTRY.Quantity(1, self._units) |
| 150 |
return qself * other |
| 151 |
|
| 152 |
if isinstance(other, Number) and other == 1: |
| 153 |
return self._REGISTRY.Quantity(other, self._units) |
| 154 |
|
| 155 |
return self._REGISTRY.Quantity(1, self._units) * other |
| 156 |
|
| 157 |
def __rmul__(self, other): |
| 158 |
return self.__mul__(other) |
| 159 |
|
| 160 |
def __truediv__(self, other): |
| 161 |
if self._check(other): |
| 162 |
if isinstance(other, self.__class__): |
| 163 |
return self.__class__(self._units / other._units) |
| 164 |
else: |
| 165 |
qself = 1 * self |
| 166 |
return qself / other |
| 167 |
# Perform division after initializing a Quantity for compatibility with with |
| 168 |
# upcast types #2126 |
| 169 |
return self._REGISTRY.Quantity(1, self._units) / other |
| 170 |
|
| 171 |
def __rtruediv__(self, other): |
| 172 |
# As PlainUnit and Quantity both handle truediv with each other rtruediv can |
| 173 |
# only be called for something different. |
| 174 |
if isinstance(other, NUMERIC_TYPES): |
| 175 |
return self._REGISTRY.Quantity(other, 1 / self._units) |
| 176 |
elif isinstance(other, UnitsContainer): |
| 177 |
return self.__class__(other / self._units) |
| 178 |
|
| 179 |
return NotImplemented |
| 180 |
|
| 181 |
__div__ = __truediv__ |
| 182 |
__rdiv__ = __rtruediv__ |
| 183 |
|
| 184 |
def __pow__(self, other) -> PlainUnit: |
| 185 |
if isinstance(other, NUMERIC_TYPES): |
| 186 |
return self.__class__(self._units**other) |
| 187 |
|
| 188 |
else: |
| 189 |
mess = f"Cannot power PlainUnit by {type(other)}" |
| 190 |
raise TypeError(mess) |
| 191 |
|
| 192 |
def __hash__(self) -> int: |
| 193 |
return self._units.__hash__() |
| 194 |
|
| 195 |
def __eq__(self, other) -> bool: |
| 196 |
# We compare to the plain class of PlainUnit because each PlainUnit class is |
| 197 |
# unique. |
| 198 |
if self._check(other): |
| 199 |
if isinstance(other, self.__class__): |
| 200 |
return self._units == other._units |
| 201 |
else: |
| 202 |
return other == self._REGISTRY.Quantity(1, self._units) |
| 203 |
|
| 204 |
elif isinstance(other, NUMERIC_TYPES): |
| 205 |
return other == self._REGISTRY.Quantity(1, self._units) |
| 206 |
|
| 207 |
else: |
| 208 |
return self._units == other |
| 209 |
|
| 210 |
def __ne__(self, other) -> bool: |
| 211 |
return not (self == other) |
| 212 |
|
| 213 |
def compare(self, other, op) -> bool: |
| 214 |
self_q = self._REGISTRY.Quantity(1, self) |
| 215 |
|
| 216 |
if isinstance(other, NUMERIC_TYPES): |
| 217 |
return self_q.compare(other, op) |
| 218 |
elif isinstance(other, (PlainUnit, UnitsContainer, dict)): |
| 219 |
return self_q.compare(self._REGISTRY.Quantity(1, other), op) |
| 220 |
|
| 221 |
return NotImplemented |
| 222 |
|
| 223 |
__lt__ = lambda self, other: self.compare(other, op=operator.lt) |
| 224 |
__le__ = lambda self, other: self.compare(other, op=operator.le) |
| 225 |
__ge__ = lambda self, other: self.compare(other, op=operator.ge) |
| 226 |
__gt__ = lambda self, other: self.compare(other, op=operator.gt) |
| 227 |
|
| 228 |
def __int__(self) -> int: |
| 229 |
return int(self._REGISTRY.Quantity(1, self._units)) |
| 230 |
|
| 231 |
def __float__(self) -> float: |
| 232 |
return float(self._REGISTRY.Quantity(1, self._units)) |
| 233 |
|
| 234 |
def __complex__(self) -> complex: |
| 235 |
return complex(self._REGISTRY.Quantity(1, self._units)) |
| 236 |
|
| 237 |
@property |
| 238 |
def systems(self): |
| 239 |
out = set() |
| 240 |
for uname in self._units.keys(): |
| 241 |
for sname, sys in self._REGISTRY._systems.items(): |
| 242 |
if uname in sys.members: |
| 243 |
out.add(sname) |
| 244 |
return frozenset(out) |
| 245 |
|
| 246 |
def from_(self, value, strict=True, name="value"): |
| 247 |
"""Converts a numerical value or quantity to this unit |
| 248 |
|
| 249 |
Parameters |
| 250 |
---------- |
| 251 |
value : |
| 252 |
a Quantity (or numerical value if strict=False) to convert |
| 253 |
strict : |
| 254 |
boolean to indicate that only quantities are accepted (Default value = True) |
| 255 |
name : |
| 256 |
descriptive name to use if an exception occurs (Default value = "value") |
| 257 |
|
| 258 |
Returns |
| 259 |
------- |
| 260 |
type |
| 261 |
The converted value as this unit |
| 262 |
|
| 263 |
""" |
| 264 |
if self._check(value): |
| 265 |
if not isinstance(value, self._REGISTRY.Quantity): |
| 266 |
value = self._REGISTRY.Quantity(1, value) |
| 267 |
return value.to(self) |
| 268 |
elif strict: |
| 269 |
raise ValueError("%s must be a Quantity" % value) |
| 270 |
else: |
| 271 |
return value * self |
| 272 |
|
| 273 |
def m_from(self, value, strict=True, name="value"): |
| 274 |
"""Converts a numerical value or quantity to this unit, then returns |
| 275 |
the magnitude of the converted value |
| 276 |
|
| 277 |
Parameters |
| 278 |
---------- |
| 279 |
value : |
| 280 |
a Quantity (or numerical value if strict=False) to convert |
| 281 |
strict : |
| 282 |
boolean to indicate that only quantities are accepted (Default value = True) |
| 283 |
name : |
| 284 |
descriptive name to use if an exception occurs (Default value = "value") |
| 285 |
|
| 286 |
Returns |
| 287 |
------- |
| 288 |
type |
| 289 |
The magnitude of the converted value |
| 290 |
|
| 291 |
""" |
| 292 |
return self.from_(value, strict=strict, name=name).magnitude |