unitful 1.0.0__tar.gz

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.
@@ -0,0 +1,16 @@
1
+ [run]
2
+ omit =
3
+ unitful/numpy_support.py
4
+
5
+ [report]
6
+ exclude_lines =
7
+ pragma: no cover
8
+ def __repr__
9
+ if self.debug:
10
+ if settings.DEBUG
11
+ raise AssertionError
12
+ raise NotImplementedError
13
+ if 0:
14
+ if __name__ == .__main__.:
15
+ if TYPE_CHECKING:
16
+ return NotImplemented
@@ -0,0 +1,70 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ tags:
8
+ - "v*.*.*"
9
+ pull_request:
10
+ branches:
11
+ - main
12
+ workflow_dispatch:
13
+
14
+ jobs:
15
+ test:
16
+ name: Test (Python ${{ matrix.python-version }})
17
+ runs-on: ubuntu-latest
18
+ strategy:
19
+ matrix:
20
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
21
+ steps:
22
+ - uses: actions/checkout@v4
23
+ - uses: actions/setup-python@v5
24
+ with:
25
+ python-version: ${{ matrix.python-version }}
26
+ - name: Install dependencies
27
+ run: |
28
+ pip install -e ".[dev]"
29
+ - name: Lint
30
+ run: ruff check unitful/
31
+ - name: Type check
32
+ run: mypy unitful/
33
+ - name: Tests
34
+ run: pytest --cov=unitful --cov-report=xml
35
+ - name: Upload coverage
36
+ uses: codecov/codecov-action@v4
37
+ if: matrix.python-version == '3.12'
38
+ with:
39
+ files: coverage.xml
40
+
41
+ build:
42
+ name: Build distribution
43
+ needs: test
44
+ runs-on: ubuntu-latest
45
+ steps:
46
+ - uses: actions/checkout@v4
47
+ - uses: actions/setup-python@v5
48
+ with:
49
+ python-version: "3.12"
50
+ - run: pip install build
51
+ - run: python -m build
52
+ - uses: actions/upload-artifact@v4
53
+ with:
54
+ name: dist
55
+ path: dist/
56
+
57
+ publish:
58
+ name: Publish to PyPI
59
+ needs: build
60
+ runs-on: ubuntu-latest
61
+ environment: release
62
+ permissions:
63
+ id-token: write
64
+ if: startsWith(github.ref, 'refs/tags/')
65
+ steps:
66
+ - uses: actions/download-artifact@v4
67
+ with:
68
+ name: dist
69
+ path: dist/
70
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,218 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ # Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ # poetry.lock
109
+ # poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ # pdm.lock
116
+ # pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ # pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # Redis
135
+ *.rdb
136
+ *.aof
137
+ *.pid
138
+
139
+ # RabbitMQ
140
+ mnesia/
141
+ rabbitmq/
142
+ rabbitmq-data/
143
+
144
+ # ActiveMQ
145
+ activemq-data/
146
+
147
+ # SageMath parsed files
148
+ *.sage.py
149
+
150
+ # Environments
151
+ .env
152
+ .envrc
153
+ .venv
154
+ env/
155
+ venv/
156
+ ENV/
157
+ env.bak/
158
+ venv.bak/
159
+
160
+ # Spyder project settings
161
+ .spyderproject
162
+ .spyproject
163
+
164
+ # Rope project settings
165
+ .ropeproject
166
+
167
+ # mkdocs documentation
168
+ /site
169
+
170
+ # mypy
171
+ .mypy_cache/
172
+ .dmypy.json
173
+ dmypy.json
174
+
175
+ # Pyre type checker
176
+ .pyre/
177
+
178
+ # pytype static type analyzer
179
+ .pytype/
180
+
181
+ # Cython debug symbols
182
+ cython_debug/
183
+
184
+ # PyCharm
185
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
186
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
187
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
188
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
189
+ # .idea/
190
+
191
+ # Abstra
192
+ # Abstra is an AI-powered process automation framework.
193
+ # Ignore directories containing user credentials, local state, and settings.
194
+ # Learn more at https://abstra.io/docs
195
+ .abstra/
196
+
197
+ # Visual Studio Code
198
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
199
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
200
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
201
+ # you could uncomment the following to ignore the entire vscode folder
202
+ # .vscode/
203
+ # Temporary file for partial code execution
204
+ tempCodeRunnerFile.py
205
+
206
+ # Ruff stuff:
207
+ .ruff_cache/
208
+
209
+ # PyPI configuration file
210
+ .pypirc
211
+
212
+ # Marimo
213
+ marimo/_static/
214
+ marimo/_lsp/
215
+ __marimo__/
216
+
217
+ # Streamlit
218
+ .streamlit/secrets.toml
unitful-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NazarHK
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.
unitful-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,112 @@
1
+ Metadata-Version: 2.4
2
+ Name: unitful
3
+ Version: 1.0.0
4
+ Summary: Physical units as first-class values with dimensional analysis
5
+ Project-URL: Homepage, https://github.com/nazarhktwitch/unitful
6
+ Project-URL: Repository, https://github.com/nazarhktwitch/unitful
7
+ Project-URL: Issues, https://github.com/nazarhktwitch/unitful/issues
8
+ License: MIT License
9
+
10
+ Copyright (c) 2026 NazarHK
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+ License-File: LICENSE
30
+ Keywords: dimensional analysis,physics,quantities,units
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: Intended Audience :: Science/Research
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Programming Language :: Python :: 3
36
+ Classifier: Programming Language :: Python :: 3.10
37
+ Classifier: Programming Language :: Python :: 3.11
38
+ Classifier: Programming Language :: Python :: 3.12
39
+ Classifier: Programming Language :: Python :: 3.13
40
+ Classifier: Topic :: Scientific/Engineering
41
+ Classifier: Typing :: Typed
42
+ Requires-Python: >=3.10
43
+ Provides-Extra: dev
44
+ Requires-Dist: mypy>=1.10; extra == 'dev'
45
+ Requires-Dist: numpy>=1.24; extra == 'dev'
46
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
47
+ Requires-Dist: pytest>=8.0; extra == 'dev'
48
+ Requires-Dist: ruff>=0.4; extra == 'dev'
49
+ Provides-Extra: numpy
50
+ Requires-Dist: numpy>=1.24; extra == 'numpy'
51
+ Description-Content-Type: text/markdown
52
+
53
+ # unitful
54
+
55
+ [![PyPI version](https://img.shields.io/pypi/v/unitful.svg?style=flat-square&color=blue)](https://pypi.org/project/unitful/)
56
+ [![Python](https://img.shields.io/pypi/pyversions/unitful.svg?style=flat-square)](https://pypi.org/project/unitful/)
57
+ [![CI](https://img.shields.io/github/actions/workflow/status/nazarhktwitch/unitful/publish.yml?style=flat-square&label=CI)](https://github.com/nazarhktwitch/unitful/actions)
58
+ [![Coverage](https://img.shields.io/codecov/c/github/nazarhktwitch/unitful?style=flat-square)](https://codecov.io/gh/nazarhktwitch/unitful)
59
+ [![License](https://img.shields.io/pypi/l/unitful.svg?style=flat-square)](LICENSE)
60
+ [![Downloads](https://img.shields.io/pypi/dm/unitful?style=flat-square&color=green)](https://pypi.org/project/unitful/)
61
+
62
+ Physical units as first-class Python values
63
+
64
+ Attach a unit to any number, arithmetic propagates units automatically
65
+ Dimension mismatches raise `DimensionError` at runtime instead of producing
66
+ silently wrong results
67
+
68
+ ## Getting Started
69
+
70
+ ```
71
+ pip install unitful
72
+ ```
73
+
74
+ ```python
75
+ from unitful import m, s, kg, km, h
76
+
77
+ distance = 100 * m
78
+ time = 9.58 * s
79
+ speed = distance / time # Quantity(10.44, 'm/s')
80
+
81
+ speed.to(km / h) # Quantity(37.58, 'km/h')
82
+ speed.to(kg) # DimensionError: [Length/Time] != [Mass]
83
+ ```
84
+
85
+ ## Features
86
+
87
+ - Dimension checking: all arithmetic validates physical dimensions and raises
88
+ `DimensionError` with a clear message on mismatch
89
+ - Unit conversion: `.to(unit)` converts between compatible units, including
90
+ offset temperature scales (`degC`, `degF`, `K`)
91
+ - NumPy integration: `np.array([...]) * m` returns a `QuantityArray`; ufuncs
92
+ and reduction functions (`np.mean`, `np.sum`, etc.) preserve units
93
+ - Decorators: `@requires` and `@returns` enforce dimensions on function
94
+ arguments and return values
95
+ - Custom units and dimensions: `define_unit` and `new_dimension` extend the
96
+ registry at runtime
97
+ - Serialization: `to_json` / `from_json` for plain-dict round-trips; pickle
98
+ and `copy` work without extra setup
99
+ - Formatting: `f"{q:.2f~P}"` (Unicode), `f"{q:.2f~L}"` (LaTeX),
100
+ `f"{q:.2f~H}"` (HTML)
101
+
102
+ ## Requirements
103
+
104
+ Python 3.10 or later. NumPy is optional; install it with:
105
+
106
+ ```
107
+ pip install "unitful[numpy]"
108
+ ```
109
+
110
+ ## License
111
+
112
+ [MIT](LICENSE)
@@ -0,0 +1,60 @@
1
+ # unitful
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/unitful.svg?style=flat-square&color=blue)](https://pypi.org/project/unitful/)
4
+ [![Python](https://img.shields.io/pypi/pyversions/unitful.svg?style=flat-square)](https://pypi.org/project/unitful/)
5
+ [![CI](https://img.shields.io/github/actions/workflow/status/nazarhktwitch/unitful/publish.yml?style=flat-square&label=CI)](https://github.com/nazarhktwitch/unitful/actions)
6
+ [![Coverage](https://img.shields.io/codecov/c/github/nazarhktwitch/unitful?style=flat-square)](https://codecov.io/gh/nazarhktwitch/unitful)
7
+ [![License](https://img.shields.io/pypi/l/unitful.svg?style=flat-square)](LICENSE)
8
+ [![Downloads](https://img.shields.io/pypi/dm/unitful?style=flat-square&color=green)](https://pypi.org/project/unitful/)
9
+
10
+ Physical units as first-class Python values
11
+
12
+ Attach a unit to any number, arithmetic propagates units automatically
13
+ Dimension mismatches raise `DimensionError` at runtime instead of producing
14
+ silently wrong results
15
+
16
+ ## Getting Started
17
+
18
+ ```
19
+ pip install unitful
20
+ ```
21
+
22
+ ```python
23
+ from unitful import m, s, kg, km, h
24
+
25
+ distance = 100 * m
26
+ time = 9.58 * s
27
+ speed = distance / time # Quantity(10.44, 'm/s')
28
+
29
+ speed.to(km / h) # Quantity(37.58, 'km/h')
30
+ speed.to(kg) # DimensionError: [Length/Time] != [Mass]
31
+ ```
32
+
33
+ ## Features
34
+
35
+ - Dimension checking: all arithmetic validates physical dimensions and raises
36
+ `DimensionError` with a clear message on mismatch
37
+ - Unit conversion: `.to(unit)` converts between compatible units, including
38
+ offset temperature scales (`degC`, `degF`, `K`)
39
+ - NumPy integration: `np.array([...]) * m` returns a `QuantityArray`; ufuncs
40
+ and reduction functions (`np.mean`, `np.sum`, etc.) preserve units
41
+ - Decorators: `@requires` and `@returns` enforce dimensions on function
42
+ arguments and return values
43
+ - Custom units and dimensions: `define_unit` and `new_dimension` extend the
44
+ registry at runtime
45
+ - Serialization: `to_json` / `from_json` for plain-dict round-trips; pickle
46
+ and `copy` work without extra setup
47
+ - Formatting: `f"{q:.2f~P}"` (Unicode), `f"{q:.2f~L}"` (LaTeX),
48
+ `f"{q:.2f~H}"` (HTML)
49
+
50
+ ## Requirements
51
+
52
+ Python 3.10 or later. NumPy is optional; install it with:
53
+
54
+ ```
55
+ pip install "unitful[numpy]"
56
+ ```
57
+
58
+ ## License
59
+
60
+ [MIT](LICENSE)
@@ -0,0 +1,66 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "unitful"
7
+ version = "1.0.0"
8
+ description = "Physical units as first-class values with dimensional analysis"
9
+ readme = "README.md"
10
+ license = { file = "LICENSE" }
11
+ requires-python = ">=3.10"
12
+ keywords = ["units", "dimensional analysis", "physics", "quantities"]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Intended Audience :: Developers",
16
+ "Intended Audience :: Science/Research",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Scientific/Engineering",
24
+ "Typing :: Typed",
25
+ ]
26
+ dependencies = []
27
+
28
+ [project.optional-dependencies]
29
+ numpy = ["numpy>=1.24"]
30
+ dev = [
31
+ "numpy>=1.24",
32
+ "pytest>=8.0",
33
+ "pytest-cov>=5.0",
34
+ "mypy>=1.10",
35
+ "ruff>=0.4",
36
+ ]
37
+
38
+ [project.urls]
39
+ Homepage = "https://github.com/nazarhktwitch/unitful"
40
+ Repository = "https://github.com/nazarhktwitch/unitful"
41
+ Issues = "https://github.com/nazarhktwitch/unitful/issues"
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ packages = ["unitful"]
45
+
46
+ [tool.pytest.ini_options]
47
+ testpaths = ["tests"]
48
+ addopts = "--tb=short"
49
+
50
+ [tool.mypy]
51
+ python_version = "3.10"
52
+ strict = true
53
+ warn_unused_ignores = true
54
+ exclude = ["numpy_support\\.py"]
55
+
56
+ [[tool.mypy.overrides]]
57
+ module = "numpy.*"
58
+ ignore_missing_imports = true
59
+
60
+ [tool.ruff]
61
+ target-version = "py310"
62
+ line-length = 100
63
+
64
+ [tool.ruff.lint]
65
+ select = ["E", "F", "I", "UP"]
66
+ ignore = ["E501"]
File without changes
@@ -0,0 +1,134 @@
1
+ """Tests for @requires and @returns decorators"""
2
+
3
+ import math
4
+ import pytest
5
+
6
+ from unitful import (
7
+ requires, returns, Dim,
8
+ DimensionError,
9
+ m, s, kg, km, h,
10
+ )
11
+
12
+
13
+ # ---------------------------------------------------------------------------
14
+ # @requires
15
+ # ---------------------------------------------------------------------------
16
+
17
+ @requires(speed=Dim("m/s"), time=Dim("s"))
18
+ def distance_traveled(speed, time):
19
+ return speed * time
20
+
21
+
22
+ def test_requires_correct_args():
23
+ result = distance_traveled(10 * m / s, 5 * s)
24
+ assert math.isclose(result.magnitude, 50.0)
25
+
26
+
27
+ def test_requires_wrong_dimension_raises():
28
+ with pytest.raises(DimensionError) as exc_info:
29
+ distance_traveled(10 * kg, 5 * s)
30
+ msg = str(exc_info.value)
31
+ assert "speed" in msg
32
+ assert "distance_traveled" in msg
33
+
34
+
35
+ def test_requires_bare_float_raises():
36
+ with pytest.raises(DimensionError) as exc_info:
37
+ distance_traveled(10, 5 * s)
38
+ msg = str(exc_info.value)
39
+ assert "bare" in msg.lower() or "no unit" in msg.lower()
40
+
41
+
42
+ def test_requires_second_param_wrong():
43
+ with pytest.raises(DimensionError) as exc_info:
44
+ distance_traveled(10 * m / s, 5 * m)
45
+ msg = str(exc_info.value)
46
+ assert "time" in msg
47
+
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # @returns
51
+ # ---------------------------------------------------------------------------
52
+
53
+ @returns(Dim("m"))
54
+ def position(x):
55
+ return x
56
+
57
+
58
+ def test_returns_correct():
59
+ result = position(5 * m)
60
+ assert result.magnitude == 5.0
61
+
62
+
63
+ def test_returns_wrong_dimension_raises():
64
+ with pytest.raises(DimensionError) as exc_info:
65
+ position(5 * kg)
66
+ msg = str(exc_info.value)
67
+ assert "position" in msg
68
+
69
+
70
+ # ---------------------------------------------------------------------------
71
+ # Stacked decorators
72
+ # ---------------------------------------------------------------------------
73
+
74
+ @requires(speed=Dim("m/s"), time=Dim("s"))
75
+ @returns(Dim("m"))
76
+ def calc_distance(speed, time):
77
+ return speed * time
78
+
79
+
80
+ def test_stacked_correct():
81
+ result = calc_distance(2 * m / s, 3 * s)
82
+ assert math.isclose(result.magnitude, 6.0)
83
+
84
+
85
+ def test_stacked_wrong_input():
86
+ with pytest.raises(DimensionError):
87
+ calc_distance(2 * kg, 3 * s)
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # Dim expression parsing
92
+ # ---------------------------------------------------------------------------
93
+
94
+ def test_dim_simple():
95
+ d = Dim("m")
96
+ from unitful.dimension import Dimension
97
+ assert d.dimension == Dimension(L=1)
98
+
99
+
100
+ def test_dim_division():
101
+ d = Dim("m/s")
102
+ from unitful.dimension import Dimension
103
+ assert d.dimension == Dimension(L=1, T=-1)
104
+
105
+
106
+ def test_dim_power():
107
+ d = Dim("m/s^2")
108
+ from unitful.dimension import Dimension
109
+ assert d.dimension == Dimension(L=1, T=-2)
110
+
111
+
112
+ def test_dim_product():
113
+ d = Dim("kg*m/s^2")
114
+ from unitful.dimension import Dimension
115
+ assert d.dimension == Dimension(M=1, L=1, T=-2)
116
+
117
+
118
+ def test_dim_unknown_raises():
119
+ with pytest.raises(ValueError):
120
+ Dim("zorgblatt")
121
+
122
+
123
+ # ---------------------------------------------------------------------------
124
+ # @requires with keyword-only call
125
+ # ---------------------------------------------------------------------------
126
+
127
+ @requires(mass=Dim("kg"))
128
+ def weigh(mass):
129
+ return mass
130
+
131
+
132
+ def test_requires_keyword_arg():
133
+ result = weigh(mass=70 * kg)
134
+ assert result.magnitude == 70.0