unitconv-azizs 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- unitconv/__init__.py +8 -0
- unitconv/__main__.py +3 -0
- unitconv/cli.py +52 -0
- unitconv/core.py +52 -0
- unitconv/currency.py +47 -0
- unitconv/py.typed +0 -0
- unitconv/quantity.py +81 -0
- unitconv/units.py +195 -0
- unitconv_azizs-0.3.0.dist-info/METADATA +127 -0
- unitconv_azizs-0.3.0.dist-info/RECORD +14 -0
- unitconv_azizs-0.3.0.dist-info/WHEEL +5 -0
- unitconv_azizs-0.3.0.dist-info/entry_points.txt +2 -0
- unitconv_azizs-0.3.0.dist-info/licenses/LICENSE +21 -0
- unitconv_azizs-0.3.0.dist-info/top_level.txt +1 -0
unitconv/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""unitconv: a simple unit and currency converter."""
|
|
2
|
+
from .core import UnitError, convert, supported_units
|
|
3
|
+
from .currency import CurrencyError, set_rates
|
|
4
|
+
from .quantity import Quantity
|
|
5
|
+
|
|
6
|
+
__all__ = ["convert", "Quantity", "UnitError", "CurrencyError",
|
|
7
|
+
"set_rates", "supported_units"]
|
|
8
|
+
__version__ = "0.3.0"
|
unitconv/__main__.py
ADDED
unitconv/cli.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from . import __version__
|
|
7
|
+
from .core import UnitError, convert, supported_units
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
11
|
+
p = argparse.ArgumentParser(
|
|
12
|
+
prog="unitconv",
|
|
13
|
+
description="Unit and currency converter.",
|
|
14
|
+
epilog="Examples: unitconv 5 km mi | unitconv 100 c f | unitconv 10 usd eur",
|
|
15
|
+
)
|
|
16
|
+
p.add_argument("value", nargs="?", type=float, help="number to convert")
|
|
17
|
+
p.add_argument("from_unit", nargs="?", help="source unit")
|
|
18
|
+
p.add_argument("to_unit", nargs="?", help="target unit")
|
|
19
|
+
p.add_argument("-p", "--precision", type=int, default=6,
|
|
20
|
+
help="decimal places (default: 6)")
|
|
21
|
+
p.add_argument("-l", "--list", action="store_true",
|
|
22
|
+
help="list supported units")
|
|
23
|
+
p.add_argument("-V", "--version", action="version", version=__version__)
|
|
24
|
+
return p
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def main(argv: list[str] | None = None) -> int:
|
|
28
|
+
parser = build_parser()
|
|
29
|
+
args = parser.parse_args(argv)
|
|
30
|
+
|
|
31
|
+
if args.list:
|
|
32
|
+
for category, units in supported_units().items():
|
|
33
|
+
print(f"{category}: {', '.join(units)}")
|
|
34
|
+
print("currency: ISO 4217 codes (USD, EUR, TJS, ...)")
|
|
35
|
+
return 0
|
|
36
|
+
|
|
37
|
+
if args.value is None or not args.from_unit or not args.to_unit:
|
|
38
|
+
parser.print_usage(sys.stderr)
|
|
39
|
+
return 2
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
result = convert(args.value, args.from_unit, args.to_unit)
|
|
43
|
+
except UnitError as exc:
|
|
44
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
45
|
+
return 1
|
|
46
|
+
|
|
47
|
+
print(f"{args.value:g} {args.from_unit} = {round(result, args.precision):g} {args.to_unit}")
|
|
48
|
+
return 0
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
if __name__ == "__main__":
|
|
52
|
+
raise SystemExit(main())
|
unitconv/core.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .currency import CurrencyError, convert_currency, is_currency
|
|
4
|
+
from .units import CATEGORIES, NONLINEAR, all_units, category_of, normalize
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class UnitError(ValueError):
|
|
8
|
+
"""Raised when a conversion is impossible."""
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def convert(value: float, from_unit: str, to_unit: str) -> float:
|
|
12
|
+
"""Convert ``value`` from ``from_unit`` to ``to_unit``.
|
|
13
|
+
|
|
14
|
+
>>> convert(1, "km", "m")
|
|
15
|
+
1000.0
|
|
16
|
+
>>> convert(0, "c", "f")
|
|
17
|
+
32.0
|
|
18
|
+
"""
|
|
19
|
+
src, dst = normalize(from_unit), normalize(to_unit)
|
|
20
|
+
|
|
21
|
+
# Non-linear categories (temperature, fuel economy)
|
|
22
|
+
for to_base, from_base in NONLINEAR.values():
|
|
23
|
+
if src in to_base and dst in from_base:
|
|
24
|
+
try:
|
|
25
|
+
return float(from_base[dst](to_base[src](value)))
|
|
26
|
+
except ZeroDivisionError:
|
|
27
|
+
raise UnitError("Division by zero during conversion") from None
|
|
28
|
+
|
|
29
|
+
# Linear categories
|
|
30
|
+
for table in CATEGORIES.values():
|
|
31
|
+
if src in table and dst in table:
|
|
32
|
+
return value * table[src] / table[dst]
|
|
33
|
+
|
|
34
|
+
cat_src, cat_dst = category_of(src), category_of(dst)
|
|
35
|
+
if cat_src and cat_dst and cat_src != cat_dst:
|
|
36
|
+
raise UnitError(
|
|
37
|
+
f"Incompatible units: '{from_unit}' ({cat_src}) and '{to_unit}' ({cat_dst})"
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# Currencies
|
|
41
|
+
if cat_src is None and cat_dst is None and is_currency(src) and is_currency(dst):
|
|
42
|
+
try:
|
|
43
|
+
return convert_currency(value, src, dst)
|
|
44
|
+
except CurrencyError as exc:
|
|
45
|
+
raise UnitError(str(exc)) from exc
|
|
46
|
+
|
|
47
|
+
raise UnitError(f"Cannot convert '{from_unit}' to '{to_unit}'")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def supported_units() -> dict[str, list[str]]:
|
|
51
|
+
"""All supported units grouped by category (currencies excluded)."""
|
|
52
|
+
return all_units()
|
unitconv/currency.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Currency conversion using exchange rates from an open API (with caching)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import time
|
|
6
|
+
import urllib.request
|
|
7
|
+
|
|
8
|
+
API_URL = "https://open.er-api.com/v6/latest/USD"
|
|
9
|
+
|
|
10
|
+
_cache: dict = {"time": 0.0, "rates": {}}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CurrencyError(ValueError):
|
|
14
|
+
"""Raised when rates cannot be fetched or a currency is unknown."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def set_rates(rates: dict[str, float]) -> None:
|
|
18
|
+
"""Set exchange rates manually (relative to USD). Useful offline and in tests."""
|
|
19
|
+
_cache.update(time=time.time(), rates={k.upper(): float(v) for k, v in rates.items()})
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def get_rates(ttl: int = 3600) -> dict[str, float]:
|
|
23
|
+
"""Get exchange rates, cached for ``ttl`` seconds."""
|
|
24
|
+
if not _cache["rates"] or time.time() - _cache["time"] > ttl:
|
|
25
|
+
try:
|
|
26
|
+
with urllib.request.urlopen(API_URL, timeout=10) as resp: # noqa: S310
|
|
27
|
+
data = json.load(resp)
|
|
28
|
+
_cache.update(time=time.time(), rates=data["rates"])
|
|
29
|
+
except Exception as exc:
|
|
30
|
+
if _cache["rates"]: # fall back to stale data if available
|
|
31
|
+
return _cache["rates"]
|
|
32
|
+
raise CurrencyError(f"Could not fetch exchange rates: {exc}") from exc
|
|
33
|
+
return _cache["rates"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def convert_currency(value: float, src: str, dst: str) -> float:
|
|
37
|
+
rates = get_rates()
|
|
38
|
+
src, dst = src.upper(), dst.upper()
|
|
39
|
+
for code in (src, dst):
|
|
40
|
+
if code not in rates:
|
|
41
|
+
raise CurrencyError(f"Unknown currency: {code}")
|
|
42
|
+
return value / rates[src] * rates[dst]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def is_currency(code: str) -> bool:
|
|
46
|
+
"""Whether ``code`` looks like a currency code (3 Latin letters)."""
|
|
47
|
+
return len(code) == 3 and code.isalpha() and code.isascii()
|
unitconv/py.typed
ADDED
|
File without changes
|
unitconv/quantity.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
|
|
5
|
+
from .core import UnitError, convert
|
|
6
|
+
from .currency import is_currency
|
|
7
|
+
from .units import category_of, normalize
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Quantity:
|
|
11
|
+
"""A value with a unit of measurement.
|
|
12
|
+
|
|
13
|
+
>>> Quantity(5, "km") + Quantity(500, "m")
|
|
14
|
+
Quantity(5.5, 'km')
|
|
15
|
+
>>> Quantity(1, "km").to("m")
|
|
16
|
+
Quantity(1000.0, 'm')
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
__slots__ = ("value", "unit")
|
|
20
|
+
|
|
21
|
+
def __init__(self, value: float, unit: str):
|
|
22
|
+
self.value = value
|
|
23
|
+
canonical = normalize(unit)
|
|
24
|
+
if category_of(canonical) is None and is_currency(canonical):
|
|
25
|
+
canonical = canonical.upper() # currency codes are stored uppercase
|
|
26
|
+
self.unit = canonical
|
|
27
|
+
|
|
28
|
+
def to(self, unit: str) -> Quantity:
|
|
29
|
+
return Quantity(convert(self.value, self.unit, unit), unit)
|
|
30
|
+
|
|
31
|
+
def _other(self, other: Quantity) -> float:
|
|
32
|
+
if not isinstance(other, Quantity):
|
|
33
|
+
raise TypeError("Operation is only supported between Quantity objects")
|
|
34
|
+
return convert(other.value, other.unit, self.unit)
|
|
35
|
+
|
|
36
|
+
def __add__(self, other):
|
|
37
|
+
return Quantity(self.value + self._other(other), self.unit)
|
|
38
|
+
|
|
39
|
+
def __sub__(self, other):
|
|
40
|
+
return Quantity(self.value - self._other(other), self.unit)
|
|
41
|
+
|
|
42
|
+
def __mul__(self, k):
|
|
43
|
+
if isinstance(k, Quantity):
|
|
44
|
+
return NotImplemented
|
|
45
|
+
return Quantity(self.value * k, self.unit)
|
|
46
|
+
|
|
47
|
+
__rmul__ = __mul__
|
|
48
|
+
|
|
49
|
+
def __truediv__(self, k):
|
|
50
|
+
if isinstance(k, Quantity):
|
|
51
|
+
return self.value / self._other(k) # ratio of quantities
|
|
52
|
+
return Quantity(self.value / k, self.unit)
|
|
53
|
+
|
|
54
|
+
def __neg__(self):
|
|
55
|
+
return Quantity(-self.value, self.unit)
|
|
56
|
+
|
|
57
|
+
def __eq__(self, other):
|
|
58
|
+
if not isinstance(other, Quantity):
|
|
59
|
+
return NotImplemented
|
|
60
|
+
try:
|
|
61
|
+
return math.isclose(self.value, self._other(other), rel_tol=1e-9)
|
|
62
|
+
except UnitError:
|
|
63
|
+
return False
|
|
64
|
+
|
|
65
|
+
def __lt__(self, other):
|
|
66
|
+
return self.value < self._other(other)
|
|
67
|
+
|
|
68
|
+
def __le__(self, other):
|
|
69
|
+
return self == other or self < other
|
|
70
|
+
|
|
71
|
+
def __gt__(self, other):
|
|
72
|
+
return self.value > self._other(other)
|
|
73
|
+
|
|
74
|
+
def __ge__(self, other):
|
|
75
|
+
return self == other or self > other
|
|
76
|
+
|
|
77
|
+
def __repr__(self):
|
|
78
|
+
return f"Quantity({self.value!r}, {self.unit!r})"
|
|
79
|
+
|
|
80
|
+
def __str__(self):
|
|
81
|
+
return f"{self.value:g} {self.unit}"
|
unitconv/units.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Unit tables.
|
|
2
|
+
|
|
3
|
+
For linear categories each unit stores a factor: how many base units
|
|
4
|
+
one such unit contains. The base unit is given in a comment.
|
|
5
|
+
Categories with non-linear conversion (temperature, fuel economy) use functions.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
|
|
11
|
+
LENGTH = { # base: metre
|
|
12
|
+
"nm": 1e-9, "um": 1e-6, "mm": 0.001, "cm": 0.01, "m": 1.0, "km": 1000.0,
|
|
13
|
+
"in": 0.0254, "ft": 0.3048, "yd": 0.9144, "mi": 1609.344,
|
|
14
|
+
"nmi": 1852.0, "ly": 9.4607304725808e15,
|
|
15
|
+
}
|
|
16
|
+
WEIGHT = { # base: kilogram
|
|
17
|
+
"ug": 1e-9, "mg": 1e-6, "g": 0.001, "kg": 1.0, "t": 1000.0,
|
|
18
|
+
"ct": 0.0002, "oz": 0.028349523125, "lb": 0.45359237, "st": 6.35029318,
|
|
19
|
+
}
|
|
20
|
+
AREA = { # base: square metre
|
|
21
|
+
"mm2": 1e-6, "cm2": 1e-4, "m2": 1.0, "km2": 1e6,
|
|
22
|
+
"sot": 100.0, "ha": 10_000.0, "ac": 4046.8564224,
|
|
23
|
+
"in2": 0.00064516, "ft2": 0.09290304, "yd2": 0.83612736, "mi2": 2589988.110336,
|
|
24
|
+
}
|
|
25
|
+
VOLUME = { # base: litre (gallons etc. are US units)
|
|
26
|
+
"ml": 0.001, "cm3": 0.001, "l": 1.0, "m3": 1000.0,
|
|
27
|
+
"tsp": 0.00492892159375, "tbsp": 0.01478676478125, "floz": 0.0295735295625,
|
|
28
|
+
"pt": 0.473176473, "qt": 0.946352946, "gal": 3.785411784, "bbl": 158.987294928,
|
|
29
|
+
}
|
|
30
|
+
SPEED = { # base: metre per second
|
|
31
|
+
"m/s": 1.0, "km/h": 1 / 3.6, "mph": 0.44704, "ft/s": 0.3048,
|
|
32
|
+
"kn": 1852 / 3600, "mach": 340.29, # Mach at sea level
|
|
33
|
+
}
|
|
34
|
+
TIME = { # base: second
|
|
35
|
+
"ns": 1e-9, "us": 1e-6, "ms": 0.001, "s": 1.0, "min": 60.0, "h": 3600.0,
|
|
36
|
+
"d": 86400.0, "wk": 604800.0,
|
|
37
|
+
"mo": 2_629_800.0, # average month (30.4375 days)
|
|
38
|
+
"yr": 31_557_600.0, # Julian year (365.25 days)
|
|
39
|
+
}
|
|
40
|
+
DATA = { # base: byte
|
|
41
|
+
"bit": 0.125, "kbit": 125.0, "mbit": 125_000.0, "gbit": 125e6,
|
|
42
|
+
"b": 1.0, "kb": 1e3, "mb": 1e6, "gb": 1e9, "tb": 1e12, "pb": 1e15,
|
|
43
|
+
"kib": 1024.0, "mib": 1024.0**2, "gib": 1024.0**3, "tib": 1024.0**4,
|
|
44
|
+
"pib": 1024.0**5,
|
|
45
|
+
}
|
|
46
|
+
PRESSURE = { # base: pascal
|
|
47
|
+
"pa": 1.0, "hpa": 100.0, "kpa": 1e3, "mpa": 1e6,
|
|
48
|
+
"mbar": 100.0, "bar": 1e5, "atm": 101_325.0,
|
|
49
|
+
"psi": 6894.757293168, "mmhg": 133.322387415, "torr": 101_325 / 760,
|
|
50
|
+
}
|
|
51
|
+
ENERGY = { # base: joule
|
|
52
|
+
"ev": 1.602176634e-19, "j": 1.0, "kj": 1e3, "mj": 1e6,
|
|
53
|
+
"cal": 4.184, "kcal": 4184.0, "wh": 3600.0, "kwh": 3.6e6,
|
|
54
|
+
"btu": 1055.05585262, "ftlb": 1.3558179483314004,
|
|
55
|
+
}
|
|
56
|
+
POWER = { # base: watt
|
|
57
|
+
"w": 1.0, "kw": 1e3,
|
|
58
|
+
"hp": 745.69987158227, # mechanical horsepower
|
|
59
|
+
"ps": 735.49875, # metric horsepower
|
|
60
|
+
"btu/h": 0.29307107,
|
|
61
|
+
}
|
|
62
|
+
ANGLE = { # base: degree
|
|
63
|
+
"arcsec": 1 / 3600, "arcmin": 1 / 60, "deg": 1.0,
|
|
64
|
+
"grad": 0.9, "rad": 180 / math.pi, "turn": 360.0,
|
|
65
|
+
}
|
|
66
|
+
FREQUENCY = { # base: hertz
|
|
67
|
+
"rpm": 1 / 60, "hz": 1.0, "khz": 1e3, "mhz": 1e6, "ghz": 1e9,
|
|
68
|
+
}
|
|
69
|
+
FORCE = { # base: newton
|
|
70
|
+
"dyn": 1e-5, "n": 1.0, "kgf": 9.80665, "lbf": 4.4482216152605,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
CATEGORIES = {
|
|
74
|
+
"length": LENGTH, "weight": WEIGHT, "area": AREA, "volume": VOLUME,
|
|
75
|
+
"speed": SPEED, "time": TIME, "data": DATA, "pressure": PRESSURE,
|
|
76
|
+
"energy": ENERGY, "power": POWER, "angle": ANGLE,
|
|
77
|
+
"frequency": FREQUENCY, "force": FORCE,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
# --- Non-linear categories: functions to and from the base unit ---
|
|
81
|
+
|
|
82
|
+
# Temperature (base: degree Celsius)
|
|
83
|
+
TO_CELSIUS = {
|
|
84
|
+
"c": lambda x: x,
|
|
85
|
+
"f": lambda x: (x - 32) * 5 / 9,
|
|
86
|
+
"k": lambda x: x - 273.15,
|
|
87
|
+
}
|
|
88
|
+
FROM_CELSIUS = {
|
|
89
|
+
"c": lambda x: x,
|
|
90
|
+
"f": lambda x: x * 9 / 5 + 32,
|
|
91
|
+
"k": lambda x: x + 273.15,
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
# Fuel economy (base: km per litre). L/100 km is inversely proportional.
|
|
95
|
+
_MPG = 1.609344 / 3.785411784 # miles per gallon -> km per litre
|
|
96
|
+
TO_KML = {
|
|
97
|
+
"km/l": lambda x: x,
|
|
98
|
+
"mpg": lambda x: x * _MPG,
|
|
99
|
+
"l/100km": lambda x: 100 / x,
|
|
100
|
+
}
|
|
101
|
+
FROM_KML = {
|
|
102
|
+
"km/l": lambda x: x,
|
|
103
|
+
"mpg": lambda x: x / _MPG,
|
|
104
|
+
"l/100km": lambda x: 100 / x,
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
NONLINEAR = {
|
|
108
|
+
"temperature": (TO_CELSIUS, FROM_CELSIUS),
|
|
109
|
+
"fuel": (TO_KML, FROM_KML),
|
|
110
|
+
}
|
|
111
|
+
TEMPERATURE = tuple(TO_CELSIUS)
|
|
112
|
+
|
|
113
|
+
# --- Aliases (Russian and English names; keys must be lowercase) ---
|
|
114
|
+
ALIASES = {
|
|
115
|
+
# length
|
|
116
|
+
"нм": "nm", "мкм": "um", "µm": "um", "мм": "mm", "см": "cm", "м": "m", "км": "km",
|
|
117
|
+
"дюйм": "in", "фут": "ft", "ярд": "yd", "миля": "mi", "мили": "mi",
|
|
118
|
+
"meter": "m", "metre": "m", "kilometer": "km", "kilometre": "km",
|
|
119
|
+
"mile": "mi", "foot": "ft", "feet": "ft", "inch": "in", "yard": "yd",
|
|
120
|
+
"световой год": "ly",
|
|
121
|
+
# weight
|
|
122
|
+
"мкг": "ug", "µg": "ug", "мг": "mg", "г": "g", "кг": "kg", "т": "t",
|
|
123
|
+
"карат": "ct", "унция": "oz", "фунт": "lb", "стоун": "st",
|
|
124
|
+
"gram": "g", "kilogram": "kg", "pound": "lb", "ounce": "oz", "tonne": "t",
|
|
125
|
+
# area
|
|
126
|
+
"мм2": "mm2", "см2": "cm2", "м2": "m2", "км2": "km2", "сотка": "sot",
|
|
127
|
+
"га": "ha", "акр": "ac", "acre": "ac", "hectare": "ha",
|
|
128
|
+
# volume
|
|
129
|
+
"мл": "ml", "см3": "cm3", "л": "l", "м3": "m3", "галлон": "gal",
|
|
130
|
+
"баррель": "bbl", "liter": "l", "litre": "l", "gallon": "gal",
|
|
131
|
+
# speed
|
|
132
|
+
"м/с": "m/s", "км/ч": "km/h", "кмч": "km/h", "kph": "km/h",
|
|
133
|
+
"узел": "kn", "knot": "kn", "фут/с": "ft/s",
|
|
134
|
+
# time
|
|
135
|
+
"нс": "ns", "мкс": "us", "µs": "us", "мс": "ms", "с": "s", "сек": "s",
|
|
136
|
+
"мин": "min", "ч": "h", "час": "h", "сут": "d", "день": "d", "нед": "wk",
|
|
137
|
+
"мес": "mo", "год": "yr",
|
|
138
|
+
"sec": "s", "second": "s", "minute": "min", "hour": "h", "day": "d",
|
|
139
|
+
"week": "wk", "month": "mo", "year": "yr",
|
|
140
|
+
# data
|
|
141
|
+
"бит": "bit", "байт": "b", "кб": "kb", "мб": "mb", "гб": "gb", "тб": "tb",
|
|
142
|
+
"пб": "pb", "кбит": "kbit", "мбит": "mbit", "гбит": "gbit",
|
|
143
|
+
"кибб": "kib", "byte": "b",
|
|
144
|
+
# pressure
|
|
145
|
+
"па": "pa", "гпа": "hpa", "кпа": "kpa", "мпа": "mpa", "мбар": "mbar",
|
|
146
|
+
"бар": "bar", "атм": "atm", "ммртст": "mmhg", "мм.рт.ст.": "mmhg",
|
|
147
|
+
"мм рт. ст.": "mmhg", "мм рт.ст.": "mmhg",
|
|
148
|
+
# energy
|
|
149
|
+
"эв": "ev", "дж": "j", "кдж": "kj", "мдж": "mj", "кал": "cal",
|
|
150
|
+
"ккал": "kcal", "втч": "wh", "квтч": "kwh", "квт·ч": "kwh", "квт*ч": "kwh",
|
|
151
|
+
"joule": "j",
|
|
152
|
+
# power
|
|
153
|
+
"вт": "w", "квт": "kw", "лс": "ps", "л.с.": "ps", "watt": "w",
|
|
154
|
+
"horsepower": "hp",
|
|
155
|
+
# angle
|
|
156
|
+
"°": "deg", "град": "deg", "градус": "deg", "рад": "rad",
|
|
157
|
+
"оборот": "turn", "degree": "deg", "radian": "rad",
|
|
158
|
+
# frequency
|
|
159
|
+
"гц": "hz", "кгц": "khz", "мгц": "mhz", "ггц": "ghz", "об/мин": "rpm",
|
|
160
|
+
# force
|
|
161
|
+
"н": "n", "кгс": "kgf", "newton": "n", "дин": "dyn",
|
|
162
|
+
# fuel economy
|
|
163
|
+
"км/л": "km/l", "л/100км": "l/100km", "л/100 км": "l/100km",
|
|
164
|
+
"l/100 km": "l/100km",
|
|
165
|
+
# temperature
|
|
166
|
+
"°c": "c", "°f": "f", "°k": "k", "°с": "c",
|
|
167
|
+
"celsius": "c", "fahrenheit": "f", "kelvin": "k",
|
|
168
|
+
"цельсий": "c", "фаренгейт": "f", "кельвин": "k",
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def normalize(unit: str) -> str:
|
|
173
|
+
"""Return the canonical (lowercase, de-aliased) unit name."""
|
|
174
|
+
unit = unit.strip().lower()
|
|
175
|
+
return ALIASES.get(unit, unit)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def category_of(unit: str) -> str | None:
|
|
179
|
+
"""Return the unit's category name, or None if unknown."""
|
|
180
|
+
unit = normalize(unit)
|
|
181
|
+
for name, (to_base, _) in NONLINEAR.items():
|
|
182
|
+
if unit in to_base:
|
|
183
|
+
return name
|
|
184
|
+
for name, table in CATEGORIES.items():
|
|
185
|
+
if unit in table:
|
|
186
|
+
return name
|
|
187
|
+
return None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def all_units() -> dict[str, list[str]]:
|
|
191
|
+
"""All supported units grouped by category (currencies excluded)."""
|
|
192
|
+
result = {name: list(table) for name, table in CATEGORIES.items()}
|
|
193
|
+
for name, (to_base, _) in NONLINEAR.items():
|
|
194
|
+
result[name] = list(to_base)
|
|
195
|
+
return result
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: unitconv-azizs
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Dependency-free unit and currency converter with a CLI and a Quantity class
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/azizs-dnv/unitconv
|
|
7
|
+
Project-URL: Issues, https://github.com/azizs-dnv/unitconv/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/azizs-dnv/unitconv/blob/main/CHANGELOG.md
|
|
9
|
+
Keywords: units,converter,currency,cli,measurement
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pytest; extra == "dev"
|
|
19
|
+
Requires-Dist: ruff; extra == "dev"
|
|
20
|
+
Requires-Dist: build; extra == "dev"
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# unitconv
|
|
24
|
+
|
|
25
|
+
[](https://github.com/YOUR_USERNAME/unitconv/actions/workflows/ci.yml)
|
|
26
|
+

|
|
27
|
+

|
|
28
|
+
|
|
29
|
+
A dependency-free Python library for converting units and currencies, with a command-line tool and a `Quantity` class that supports arithmetic.
|
|
30
|
+
|
|
31
|
+
## Installation
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install unitconv-azizs # once published to PyPI
|
|
35
|
+
# or from source:
|
|
36
|
+
git clone https://github.com/azizs-dnv/unitconv.git
|
|
37
|
+
cd unitconv
|
|
38
|
+
pip install -e ".[dev]"
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Quick start
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from unitconv import convert, Quantity
|
|
45
|
+
|
|
46
|
+
convert(5, "km", "mi") # 3.1068...
|
|
47
|
+
convert(100, "c", "f") # 212.0
|
|
48
|
+
convert(2, "kg", "lb") # 4.409...
|
|
49
|
+
convert(1, "atm", "psi") # 14.69...
|
|
50
|
+
convert(7, "l/100km", "mpg") # 33.6...
|
|
51
|
+
convert(10, "usd", "tjs") # at the current exchange rate
|
|
52
|
+
|
|
53
|
+
# Quantities with units
|
|
54
|
+
d = Quantity(5, "km") + Quantity(500, "m") # Quantity(5.5, 'km')
|
|
55
|
+
d.to("mi")
|
|
56
|
+
Quantity(1, "km") > Quantity(500, "m") # True
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Command line
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
unitconv 5 km mi
|
|
63
|
+
unitconv 100 c f
|
|
64
|
+
unitconv 2500 kcal kj
|
|
65
|
+
unitconv 10 usd eur -p 2
|
|
66
|
+
unitconv --list
|
|
67
|
+
python -m unitconv 1 gb mib
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Supported categories
|
|
71
|
+
|
|
72
|
+
| Category | Units |
|
|
73
|
+
|---|---|
|
|
74
|
+
| Length | nm, um, mm, cm, m, km, in, ft, yd, mi, nmi, ly |
|
|
75
|
+
| Weight | ug, mg, g, kg, t, ct, oz, lb, st |
|
|
76
|
+
| Area | mm2, cm2, m2, km2, sot, ha, ac, in2, ft2, yd2, mi2 |
|
|
77
|
+
| Volume | ml, cm3, l, m3, tsp, tbsp, floz, pt, qt, gal, bbl |
|
|
78
|
+
| Speed | m/s, km/h, mph, ft/s, kn, mach |
|
|
79
|
+
| Time | ns, us, ms, s, min, h, d, wk, mo, yr |
|
|
80
|
+
| Data | bit, kbit, mbit, gbit, b, kb, mb, gb, tb, pb, kib, mib, gib, tib, pib |
|
|
81
|
+
| Pressure | pa, hpa, kpa, mpa, mbar, bar, atm, psi, mmhg, torr |
|
|
82
|
+
| Energy | ev, j, kj, mj, cal, kcal, wh, kwh, btu, ftlb |
|
|
83
|
+
| Power | w, kw, hp, ps, btu/h |
|
|
84
|
+
| Angle | arcsec, arcmin, deg, grad, rad, turn |
|
|
85
|
+
| Frequency | rpm, hz, khz, mhz, ghz |
|
|
86
|
+
| Force | dyn, n, kgf, lbf |
|
|
87
|
+
| Temperature | c, f, k |
|
|
88
|
+
| Fuel economy | km/l, mpg, l/100km |
|
|
89
|
+
| Currencies | ISO 4217 codes (USD, EUR, TJS, ...) |
|
|
90
|
+
|
|
91
|
+
Unit names are case-insensitive. English names (`kilometer`, `pound`, `knot`) and Russian names (`км`, `кг`, `ккал`, `л.с.`, `мм рт. ст.`) are accepted as aliases. Gallons, pints and barrels are US units. Mach, month and year are approximations (see comments in `units.py`).
|
|
92
|
+
|
|
93
|
+
## Currencies
|
|
94
|
+
|
|
95
|
+
Exchange rates come from an open API ([open.er-api.com](https://www.exchangerate-api.com/docs/free)) and are cached for one hour. Please check the service's terms of use. For offline use and tests, set rates manually:
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
from unitconv import set_rates
|
|
99
|
+
set_rates({"USD": 1, "EUR": 0.92, "TJS": 10.7})
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Errors
|
|
103
|
+
|
|
104
|
+
All conversion errors raise `UnitError`:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
from unitconv import convert, UnitError
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
convert(1, "km", "kg")
|
|
111
|
+
except UnitError as e:
|
|
112
|
+
print(e) # Incompatible units: 'km' (length) and 'kg' (weight)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Development
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
pip install -e ".[dev]"
|
|
119
|
+
ruff check .
|
|
120
|
+
pytest
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for details and [CHANGELOG.md](CHANGELOG.md) for release history.
|
|
124
|
+
|
|
125
|
+
## License
|
|
126
|
+
|
|
127
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
unitconv/__init__.py,sha256=xxTHALbf_3NHS4cNhOPlCuUEzar2zBusu5QSrIgZcE4,316
|
|
2
|
+
unitconv/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
|
|
3
|
+
unitconv/cli.py,sha256=JFGuYvu4EXN_ejkH5t84CQ7ULFol48tIKwj-zRF_XW8,1695
|
|
4
|
+
unitconv/core.py,sha256=Q_ha1SXKC4yOt5dYlvCyt0CikQuipqpwgu1a4o2U2QQ,1746
|
|
5
|
+
unitconv/currency.py,sha256=MI5yS-r6UqNrhmfgVDZCURpZGl0MacEz5lJusEDnCsI,1691
|
|
6
|
+
unitconv/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
unitconv/quantity.py,sha256=GXoDyU0y0Bb1QKj4ZhJQyp1iOeTVPwsWMMeUSF_lHOw,2374
|
|
8
|
+
unitconv/units.py,sha256=0tZbwKuv7QSz-foFV1NUAg5-rCpUHigAefKVPcn4ssc,7598
|
|
9
|
+
unitconv_azizs-0.3.0.dist-info/licenses/LICENSE,sha256=2bYXNq4AXqwc8L7xuaUEn9Eijz-L0Zov9zYmqWcgnZM,1061
|
|
10
|
+
unitconv_azizs-0.3.0.dist-info/METADATA,sha256=8HzXeTo2fCFsF38nij9myhDTbarWIlFkw2k2v_HgKo8,4026
|
|
11
|
+
unitconv_azizs-0.3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
unitconv_azizs-0.3.0.dist-info/entry_points.txt,sha256=LN87BtqqKZ5KXxYX80mHOcbW8E3gj0jR4j5wQ0PVQYQ,47
|
|
13
|
+
unitconv_azizs-0.3.0.dist-info/top_level.txt,sha256=VMEcJ9HEkEUBIjToMOapuPBDAjPNLj7QjF9eFTyhBfA,9
|
|
14
|
+
unitconv_azizs-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Aziz
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
unitconv
|