TypedUnit 0.0.3__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.
TypedUnit/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ try:
2
+ from ._version import version as __version__ # noqa: F401
3
+
4
+ except ImportError:
5
+ __version__ = "0.0.0"
6
+
7
+
8
+ from .units import *
9
+ from .helper import validate_units
TypedUnit/_version.py ADDED
@@ -0,0 +1,34 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = [
5
+ "__version__",
6
+ "__version_tuple__",
7
+ "version",
8
+ "version_tuple",
9
+ "__commit_id__",
10
+ "commit_id",
11
+ ]
12
+
13
+ TYPE_CHECKING = False
14
+ if TYPE_CHECKING:
15
+ from typing import Tuple
16
+ from typing import Union
17
+
18
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
19
+ COMMIT_ID = Union[str, None]
20
+ else:
21
+ VERSION_TUPLE = object
22
+ COMMIT_ID = object
23
+
24
+ version: str
25
+ __version__: str
26
+ __version_tuple__: VERSION_TUPLE
27
+ version_tuple: VERSION_TUPLE
28
+ commit_id: COMMIT_ID
29
+ __commit_id__: COMMIT_ID
30
+
31
+ __version__ = version = '0.0.3'
32
+ __version_tuple__ = version_tuple = (0, 0, 3)
33
+
34
+ __commit_id__ = commit_id = None
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ from pathlib import Path
5
+ import TypedUnit
6
+
7
+
8
+ __all__ = [
9
+ 'root_path',
10
+ 'project_path',
11
+ 'doc_path',
12
+ 'doc_css_path',
13
+ ]
14
+
15
+ root_path = Path(TypedUnit.__path__[0])
16
+
17
+ project_path = root_path.parents[0]
18
+
19
+ example_directory = root_path.joinpath('examples')
20
+
21
+ doc_path = project_path.joinpath('docs')
22
+
23
+ examples_path = project_path.joinpath('docs/examples')
24
+
25
+ doc_css_path = doc_path.joinpath('source/_static/default.css')
26
+
27
+
28
+ if __name__ == '__main__':
29
+ for path_name in __all__:
30
+ path = locals()[path_name]
31
+ print(path)
32
+ assert path.exists(), f"Path {path_name} do not exists."
33
+
34
+ # -
TypedUnit/helper.py ADDED
@@ -0,0 +1,20 @@
1
+ from TypedUnit.units import BaseUnit
2
+
3
+ from typing import get_type_hints
4
+
5
+ def validate_units(function):
6
+ def wrapper(*args, **kwargs):
7
+ hints = get_type_hints(function)
8
+
9
+ for arg, hint in zip(args, hints.values()):
10
+ if isinstance(hint, BaseUnit):
11
+ hint.check(arg)
12
+
13
+ for kwarg_name, kwarg_value in kwargs.items():
14
+ if kwarg_name in hints:
15
+ hint = hints[kwarg_name]
16
+ if issubclass(hint, BaseUnit):
17
+ hint.check(kwarg_value)
18
+
19
+ return function(*args, **kwargs)
20
+ return wrapper
TypedUnit/units.py ADDED
@@ -0,0 +1,106 @@
1
+ # Initialize a unit registry
2
+ from pint import Quantity, UnitRegistry
3
+
4
+ ureg = UnitRegistry()
5
+
6
+ # _scaled_units_str_list = [
7
+ # 'watt', 'volt', 'meter', 'second', 'liter', 'hertz', 'ohm', 'ampere', 'joule', 'coulomb', 'kelvin', 'celsius', 'degree', 'particle'
8
+ # ]
9
+
10
+ # for _units_str in _scaled_units_str_list:
11
+ # for scale in ['femto', 'pico', 'nano', 'micro', 'milli', '', 'kilo', 'mega']:
12
+ # _unit = scale + _units_str
13
+ # globals()[_unit] = getattr(ureg, _unit)
14
+
15
+
16
+ ureg.define("photoelectron = [Float64]") # Define a custom unit 'photoelectron'
17
+ ureg.define("event = [Int64]") # Define a custom unit 'events'
18
+ ureg.define("sqrt_hertz = Hz**0.5")
19
+ ureg.define("bit_bins = ![Int64]")
20
+
21
+ class UnitMeta(type):
22
+ """
23
+ Metaclass that makes isinstance(x, SomeUnit) return True
24
+ when x is a pint.Quantity with the right dimensionality.
25
+ """
26
+ def __instancecheck__(cls, obj):
27
+ if not isinstance(obj, Quantity):
28
+ return False
29
+ expected = getattr(cls, "_expected_dim", None)
30
+ if expected is None:
31
+ return False
32
+ # Use pint's dimensionality check; accepts strings like "energy"
33
+ return obj.check(expected)
34
+
35
+ class BaseUnit(metaclass=UnitMeta):
36
+ _expected_dim: str | None = None
37
+
38
+ @classmethod
39
+ def check(cls, value):
40
+ assert isinstance(value, Quantity), f"Expected a pint Quantity instance, got {type(value)}"
41
+ assert value.check(cls._expected_dim), f"Value units {value.dimensionality} do not match {cls.__name__} units"
42
+ return value
43
+
44
+
45
+ class Energy(BaseUnit):
46
+ """Quantity specifically for energy units."""
47
+ _expected_dim = "joule"
48
+
49
+ class Time(BaseUnit):
50
+ """Quantity specifically for time units."""
51
+ _expected_dim = "second"
52
+
53
+ class Power(BaseUnit):
54
+ """Quantity specifically for power units."""
55
+ _expected_dim = "watt"
56
+
57
+ class Voltage(BaseUnit):
58
+ """Quantity specifically for voltage units."""
59
+ _expected_dim = "volt"
60
+
61
+ class Current(BaseUnit):
62
+ """Quantity specifically for current units."""
63
+ _expected_dim = "ampere"
64
+
65
+ class Resistance(BaseUnit):
66
+ """Quantity specifically for resistance units."""
67
+ _expected_dim = "ohm"
68
+
69
+ class Temperature(BaseUnit):
70
+ """Quantity specifically for temperature units."""
71
+ _expected_dim = "kelvin"
72
+
73
+ class Length(BaseUnit):
74
+ """Quantity specifically for length units."""
75
+ _expected_dim = "meter"
76
+
77
+ class Volume(BaseUnit):
78
+ """Quantity specifically for volume units."""
79
+ _expected_dim = "liter"
80
+
81
+ class FlowRate(BaseUnit):
82
+ """Quantity specifically for flow rate units."""
83
+ _expected_dim = "liter / second"
84
+
85
+ class Frequency(BaseUnit):
86
+ """Quantity specifically for frequency units."""
87
+ _expected_dim = "hertz"
88
+
89
+ class Angle(BaseUnit):
90
+ """Quantity specifically for angle units."""
91
+ _expected_dim = "degree"
92
+
93
+ class Mass(BaseUnit):
94
+ """Quantity specifically for mass units."""
95
+ _expected_dim = "kilogram"
96
+
97
+ class RefractiveIndex(BaseUnit):
98
+ """Quantity specifically for refractive index units."""
99
+ _expected_dim = "refractive_index_units"
100
+
101
+ class Dimensionless(BaseUnit):
102
+ """Quantity specifically for dimensionless units."""
103
+ _expected_dim = ""
104
+
105
+
106
+
TypedUnit/utils.py ADDED
File without changes
@@ -0,0 +1,262 @@
1
+ Metadata-Version: 2.4
2
+ Name: TypedUnit
3
+ Version: 0.0.3
4
+ Summary: A package wrapping pint for handling typed units in Python.
5
+ Author-email: Martin Poinsinet de Sivry-Houle <martin.poinsinet.de.sivry@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2020 Martin de Sivry
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/MartinPdeS/TypedUnit
29
+ Project-URL: Documentation, https://martinpdes.github.io/TypedUnit/
30
+ Project-URL: Repository, https://github.com/MartinPdeS/TypedUnit.git
31
+ Keywords: typed units,pint,physical quantities
32
+ Classifier: Programming Language :: Python
33
+ Classifier: Programming Language :: Python :: 3
34
+ Classifier: Programming Language :: Python :: 3.11
35
+ Classifier: Programming Language :: Python :: 3.12
36
+ Classifier: Programming Language :: Python :: Implementation :: CPython
37
+ Classifier: Development Status :: 4 - Beta
38
+ Classifier: Topic :: Scientific/Engineering :: Physics
39
+ Classifier: License :: OSI Approved :: MIT License
40
+ Classifier: Intended Audience :: Science/Research
41
+ Requires-Python: >=3.10
42
+ Description-Content-Type: text/x-rst
43
+ License-File: LICENSE
44
+ Requires-Dist: pint
45
+ Requires-Dist: numpy
46
+ Requires-Dist: matplotlib
47
+ Provides-Extra: testing
48
+ Requires-Dist: pytest<9.0,>=7.4; extra == "testing"
49
+ Requires-Dist: pytest-cov<7,>=2; extra == "testing"
50
+ Requires-Dist: pytest-json-report~=1.5; extra == "testing"
51
+ Requires-Dist: flake8==7.3.0; extra == "testing"
52
+ Requires-Dist: coverage~=7.6; extra == "testing"
53
+ Provides-Extra: documentation
54
+ Requires-Dist: numpydoc~=1.8; extra == "documentation"
55
+ Requires-Dist: sphinx>=6; extra == "documentation"
56
+ Requires-Dist: sphinx-gallery~=0.17; extra == "documentation"
57
+ Requires-Dist: sphinx-rtd-theme<4,>=2; extra == "documentation"
58
+ Requires-Dist: pydata-sphinx-theme~=0.15; extra == "documentation"
59
+ Dynamic: license-file
60
+
61
+ TypedUnits
62
+ ===========
63
+
64
+ |python| |docs| |coverage| |PyPi| |PyPi_download|
65
+
66
+ **Type-safe physical units for Python**
67
+
68
+ TypedUnits is a Python library that extends Pint with type safety and validation capabilities. It allows you to create unit-aware types that work seamlessly with Python's type system and provide runtime validation for physical quantities.
69
+
70
+ **Key Features:**
71
+
72
+ - **Type Safety**: Use `isinstance()` checks with unit types like `Energy`, `Time`, `Power`
73
+ - **Automatic Validation**: Function decorators for unit validation based on type annotations
74
+ - **Pydantic Integration**: Full compatibility with Pydantic dataclasses and models
75
+ - **Normal Pint Usage**: Keep your existing Pint code - just add type safety on top
76
+
77
+ ----
78
+
79
+ **Quick Example**
80
+
81
+ .. code-block:: python
82
+
83
+ from TypedUnits import Energy, Time, Power, validate, ureg
84
+
85
+ # Normal Pint instantiation
86
+ energy = 100 * ureg.joule
87
+ time = 10 * ureg.second
88
+
89
+ # But now isinstance works!
90
+ assert isinstance(energy, Energy) # True
91
+ assert isinstance(time, Time) # True
92
+
93
+ @validate_units
94
+ def calculate_power(energy: Energy, time: Time) -> Power:
95
+ """Function with automatic unit validation."""
96
+ return (energy / time).to(ureg.watt)
97
+
98
+ # This works
99
+ power = calculate_power(energy, time)
100
+ print(f"Power: {power}")
101
+
102
+ # This fails with clear error message
103
+ length = 5 * ureg.meter
104
+ # calculate_power(length, time) # TypeError: Expected Energy, got Length
105
+
106
+ ----
107
+
108
+ **Installation**
109
+
110
+ .. code-block:: bash
111
+
112
+ pip install TypedUnits
113
+
114
+ ----
115
+
116
+ **Basic Usage**
117
+
118
+ **Unit Type Checking**
119
+
120
+ .. code-block:: python
121
+
122
+ from TypedUnits import Energy, Length, Mass, ureg
123
+
124
+ # Create quantities the normal way
125
+ kinetic_energy = 0.5 * 10 * ureg.kilogram * (5 * ureg.meter / ureg.second)**2
126
+ potential_energy = 10 * ureg.kilogram * 9.81 * ureg.meter / ureg.second**2 * 2 * ureg.meter
127
+ distance = 100 * ureg.meter
128
+ mass = 5 * ureg.kilogram
129
+
130
+ # Type checking works
131
+ assert isinstance(kinetic_energy, Energy)
132
+ assert isinstance(potential_energy, Energy)
133
+ assert isinstance(distance, Length)
134
+ assert isinstance(mass, Mass)
135
+
136
+ **Function Validation**
137
+
138
+ .. code-block:: python
139
+
140
+ from TypedUnits import validate_units, Energy, Time, Power
141
+
142
+ @validate_units
143
+ def calculate_work(power: Power, time: Time) -> Energy:
144
+ """Calculate work from power and time."""
145
+ return (power * time).to(ureg.joule)
146
+
147
+ power = 1500 * ureg.watt
148
+ time = 3600 * ureg.second # 1 hour
149
+ work = calculate_work(power, time)
150
+ print(f"Work done: {work.to(ureg.kilowatt_hour)}")
151
+
152
+ **Pydantic Integration**
153
+
154
+ .. code-block:: python
155
+
156
+ from TypedUnits import Energy, Length, Mass
157
+ from pydantic.dataclasses import dataclass
158
+
159
+ @dataclass
160
+ class Projectile:
161
+ kinetic_energy: Energy
162
+ height: Length
163
+ mass: Mass
164
+
165
+ # Automatic validation on creation
166
+ projectile = Projectile(
167
+ kinetic_energy=500 * ureg.joule,
168
+ height=10 * ureg.meter,
169
+ mass=2 * ureg.kilogram
170
+ )
171
+
172
+ ----
173
+
174
+ **Available Unit Types**
175
+
176
+ TypedUnits includes common physical unit types:
177
+
178
+ - **Mechanical**: `Energy`, `Power`, `Force`, `Pressure`
179
+ - **Spatial**: `Length`, `Area`, `Volume`, `Angle`
180
+ - **Temporal**: `Time`, `Frequency`
181
+ - **Thermal**: `Temperature`, `ThermalConductivity`
182
+ - **Electrical**: `Current`, `Voltage`, `Resistance`, `Capacitance`
183
+ - **Optical**: `RefractiveIndex`, `Wavelength`, `ElectricField`
184
+ - **Mass**: `Mass`, `Density`, `MolarMass`
185
+
186
+ ----
187
+
188
+ **Advanced Features**
189
+
190
+ **Custom Unit Types**
191
+
192
+ .. code-block:: python
193
+
194
+ from TypedUnits import create_unit_type
195
+
196
+ # Create your own unit types
197
+ MagneticField = create_unit_type('MagneticField', '[magnetic_flux_density]')
198
+
199
+ field = 1.5 * ureg.tesla
200
+ assert isinstance(field, MagneticField)
201
+
202
+ **Flexible Validation**
203
+
204
+ .. code-block:: python
205
+
206
+ from TypedUnits import validate_enhanced
207
+
208
+ @validate_enhanced(strict_mode=False, convert_types=True)
209
+ def flexible_function(energy: Energy, count: int) -> str:
210
+ """Function with flexible validation options."""
211
+ return f"Energy per item: {energy / count}"
212
+
213
+ ----
214
+
215
+ **Requirements**
216
+
217
+ - Python ≥ 3.8
218
+ - Pint ≥ 0.20
219
+ - Pydantic ≥ 2.0 (optional, for dataclass integration)
220
+
221
+ ----
222
+
223
+ **Testing**
224
+
225
+ .. code-block:: bash
226
+
227
+ git clone https://github.com/MartinPdeS/TypedUnits.git
228
+ cd TypedUnits
229
+ pip install -e ".[testing]"
230
+ pytest
231
+
232
+ ----
233
+
234
+ **Contributing**
235
+
236
+ TypedUnits is open source and contributions are welcome! Whether you're fixing bugs, adding new unit types, or improving documentation, your help is appreciated.
237
+
238
+ **Author:** `Martin Poinsinet de Sivry-Houle <https://github.com/MartinPdeS>`_
239
+
240
+ **Email:** `martin.poinsinet-de-sivry@polymtl.ca <mailto:martin.poinsinet-de-sivry@polymtl.ca?subject=TypedUnits>`_
241
+
242
+ ----
243
+
244
+ .. |python| image:: https://img.shields.io/pypi/pyversions/typedunits.svg
245
+ :target: https://www.python.org/
246
+ :alt: Python version
247
+
248
+ .. |PyPi| image:: https://badge.fury.io/py/TypedUnits.svg
249
+ :target: https://pypi.org/project/TypedUnits/
250
+ :alt: PyPi
251
+
252
+ .. |PyPi_download| image:: https://img.shields.io/pypi/dm/typedunits.svg
253
+ :target: https://pypistats.org/packages/typedunits
254
+ :alt: PyPi download statistics
255
+
256
+ .. |docs| image:: https://github.com/martinpdes/typedunits/actions/workflows/deploy_documentation.yml/badge.svg
257
+ :target: https://martinpdes.github.io/TypedUnits/
258
+ :alt: Documentation Status
259
+
260
+ .. |coverage| image:: https://raw.githubusercontent.com/MartinPdeS/TypedUnits/python-coverage-comment-action-data/badge.svg
261
+ :target: https://htmlpreview.github.io/?https://github.com/MartinPdeS/TypedUnits/blob/python-coverage-comment-action-data/htmlcov/index.html
262
+ :alt: Unittest coverage
@@ -0,0 +1,11 @@
1
+ TypedUnit/__init__.py,sha256=rW7CVYOuzJNfo6fm7xblpEkP5L5GDzbOse32vGSUl38,172
2
+ TypedUnit/_version.py,sha256=pBZsQt6tlL02W-ri--X_4JCubpAK7jjCSnOmUp_isjc,704
3
+ TypedUnit/directories.py,sha256=xxaISqOoX8imaYcHZRieg_4KCuRJNp3WMv7Vfi9nlkE,654
4
+ TypedUnit/helper.py,sha256=GDv_LU145qLEFmD2RJqYoYEYL6uT8xq0helRmryzmUg,590
5
+ TypedUnit/units.py,sha256=ys-DB_d37HaUez1SxvKfPS2baLi7XFcn04crzyQOIRg,3166
6
+ TypedUnit/utils.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ typedunit-0.0.3.dist-info/licenses/LICENSE,sha256=U6YG4UEW9XJzHa53oijR0qw6JNN_SZ38WOBmYn3NPd0,1072
8
+ typedunit-0.0.3.dist-info/METADATA,sha256=AJ56QRg6IMb8HYlz6UThbSxCpDtW0JtOj4N4jINYH5k,8595
9
+ typedunit-0.0.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
10
+ typedunit-0.0.3.dist-info/top_level.txt,sha256=rlfYVNCpYMT-pzSijzyvXMPbE-V-DN0Z2YWw4uHwUnc,10
11
+ typedunit-0.0.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Martin de Sivry
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
+ TypedUnit