Skip to content
Commits on Source (2)
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = tab
[*.{yml,yaml,cfg}]
indent_style = space
indent_size = 2
*.py[co]
*.tar
*.tar.*
*.whl
*_cache
[general]
ignore=body-trailing-whitespace,body-is-missing
regex-style-search=True
[author-valid-email]
regex=@[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9](\.[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])+$
[ignore-body-lines]
regex="^(Fixes|Closes):?\s+[#][0-9]+"
# vim:ft=cfg
default_stages: [commit]
repos:
- repo: meta
hooks:
- id: check-hooks-apply
- id: check-useless-excludes
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: check-added-large-files
- id: check-case-conflict
- id: check-merge-conflict
- id: check-toml
- id: check-yaml
- id: debug-statements
- id: destroyed-symlinks
- id: end-of-file-fixer
stages: [commit, manual]
- id: fix-byte-order-marker
- id: fix-encoding-pragma
args: [--remove]
- id: mixed-line-ending
args: [--fix=lf]
stages: [commit, manual]
- id: trailing-whitespace
exclude_types: [markdown, plain-text]
stages: [commit, manual]
- repo: https://github.com/jorisroovers/gitlint
rev: v0.19.1
hooks:
- id: gitlint
- repo: https://code.kodo.org.uk/dom/pre-commit-hooks
rev: v0.6.1
hooks:
- id: check-executable-modes
- id: check-for-squash
- id: copyright-notice
args: [--min-size=1000]
files: ^kodo/.*
stages: [commit, manual]
- id: protect-first-parent
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.10.0
hooks:
- id: python-no-eval
- id: python-no-log-warn
- id: python-use-type-annotations
- repo: https://github.com/hakancelikdev/unimport
rev: 1.2.1
hooks:
- id: unimport
args: [--remove]
types: []
types_or: [python, pyi]
additional_dependencies: [libcst >=0.4.0]
stages: [commit, manual]
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
stages: [commit, manual]
- repo: https://github.com/asottile/add-trailing-comma
rev: v3.1.0
hooks:
- id: add-trailing-comma
args: [--py36-plus]
types: []
types_or: [python, pyi]
stages: [commit, manual]
- repo: https://code.kodo.org.uk/dom/pre-commit-pytest
rev: v1.0
hooks:
- id: pytest
types_or: [python, markdown]
stages: [commit, manual]
args: [--doctest-modules, --doctest-continue-on-failure]
- id: pytest
args: [test.py]
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.2
hooks:
- id: ruff
args: [--fix, --unsafe-fixes]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.11.2
hooks:
- id: mypy
args: [--follow-imports=silent, kodo]
pass_filenames: false
line-length = 92
indent-width = 1 # Used for line length violations
[lint]
select = [
# pyflakes
# --------
# ENABLE "Undefined name %s in __all__"
"F822",
# ENABLE "Local variable %s ... referenced before assignment"
"F823",
# ENABLE "Local variable %s is assigned to but never used"
"F841",
# ENABLE "raise NotImplemented should be raise NotImplementedError"
# mypy has particular trouble with this one:
# https://github.com/python/mypy/issues/5710
"F901",
# pycodestyle
# -----------
# Warnings not considered, many are not relevant to Python ~=3.9 and will
# cause syntax errors anyway, others concern whitespace which is fixed by
# a pre-commit hook.
"E",
# mccabe
# ------
"C90",
# pydocstyle
# ----------
# Missing docstrings
"D1",
# Whitespace Issues
"D2",
# ENABLE "Use “””triple double quotes”””"
"D300",
# First line should be descriptive, imperative and capitalised
"D401", "D402", "D403", "D404",
# ENABLE "Function/Method decorated with @overload shouldn’t contain a docstring"
"D418",
# flake8-bugbear
# --------------
# The bulk of bugbear's checks are useful
"B0",
# Various others
# --------------
"UP", "BLE", "FBT", "A", "COM", "C4", "DTZ", "ISC", "LOG", "G", "PIE", "T",
"Q", "RSE", "RET", "SLF", "SLOT", "SIM", "TD", "ANN", #"FA",
# Nice to have, needs fixing in several places though...
# "EM", "TCH", "PTH", "PGH",
]
ignore = [
# pycodestyle
# -----------
# DISABLE "Indentation contains mixed spaces and tabs"
# Will cause a syntax error if critical, otherwise in docstrings it is
# sometimes nice to use different indentation for "outer" (code) indentation
# and "inner" (documentation) indentation.
"E101",
# DISABLE "Continuation line missing indentation or outdented"
# "E122",
# DISABLE "Missing whitespace around bitwise or shift operator"
"E227",
# DISABLE "missing whitespace around arithmetic operator"
"E226",
# DISABLE "Line too long"
# Prefer B950 implementation
"E501",
# DISABLE "Multiple statements on one line (colon)"
"E701",
# DISABLE "Multiple statements on one line (def)"
# Doesn't work well with @overload definitions
# "E704",
# pydocstyle
# ----------
# DISABLE "Missing docstring in magic method"
# Magic/dunder methods are well-known
"D105",
# DISABLE "Missing docstring in __init__"
# Document basic construction in the class docstring
"D107",
# DISABLE "One-line docstring should fit on one line with quotes"
# Prefer top-and-bottom style always
"D200",
# DISABLE "1 blank line required before class docstring"
"D203",
# DISABLE "Docstring should be indented with spaces, not tabs"
# Tabs, absolutely always
"D206",
# DISABLE "Multi-line docstring summary should start at the first line"
"D212",
# flake8-bugbear
# --------------
# DISABLE "Do not use mutable data structures for argument defaults [...]"
# Would be nice if could take into account use as a non-mutable type
"B006",
# DISABLE "Loop control variable `self` overrides iterable it iterates"
# Bit buggy, and type checker should catch it.
"B020",
# DISABLE "release is an empty method in an abstract base class, [...]"
# Until abstract methods are optional, empty optional "abstract" methods
# stay
"B027",
# Use named-tuples (preferably class based) for data-only classes
# "B903",
# Replacement for E501
# "B950",
# flake8-return
# -------------
# DISABLE "missing explicit return at the end of function able to return
# non-None value"
# Mypy will report this, plugin also cannot do exhaustiveness check of match
# block, leading to false-positives.
"RET503",
# DISABLE "Missing type annotation for `%` in {method|classmethod}"
# Don't type 'self' or 'cls'
"ANN101", "ANN102",
# DISABLE "Boolean positional value in function call"
# Too many stdlib functions take a single positional-only boolean. ruff
# can't interpret function signatures to ignore these and doesn't understand
# types to allow-list methods.
"FBT003",
# DISABLE "Implicitly concatenated string literals over multiple lines"
# It sometimes looks better to do this than introduce unecessary
# parentheses.
"ISC002",
# Unfortunately a lot of single quotes strings used in this project already
"Q000",
]
[lint.per-file-ignores]
"test*" = ["D1"]
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
Setup and configuration for pytest
"""
import time
from unittest.mock import Mock
import pytest
@pytest.fixture(autouse=True)
def add_time_mock(doctest_namespace: dict[str, object]) -> None:
"""
Add a doctest mock for `time.sleep()`
"""
time.sleep = Mock(return_value=None)
# Copyright 2024 Dom Sekotill <dom.sekotill@kodo.org.uk>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Types for representing physical quantities, which have a magnitude and a unit
Defining Units
--------------
Unit types for quantities are created by subclassing the `QuantityUnit` enum base:
>>> class Time(QuantityUnit):
... MILLISECONDS = 1
... SECONDS = 1000
... MINUTES = 60 * SECONDS
>>> class Distance(QuantityUnit):
... MILLIMETERS = 1
... CENTIMETERS = 10 * MILLIMETERS
... METERS = 100 * CENTIMETERS
... KILOMETERS = 1000 * METERS
... INCH = 24 * MILLIMETERS
... HALF_INCH = INCH // 2 # Hey! Hands off
... QUARTER_INCH = INCH // 4
The enum members form units of relative size to each other. They MUST be integers so
typically the smallest (highest precision) unit is `1` and the others are some multiple of
it. Note that the designated 'unit' can be changed without breaking dependant code (as long
as the code is using the quantities right). In this case the unitary value is 0.5mm:
>>> class Distance(QuantityUnit):
... MILLIMETERS = 2 # Scaled to allow SIXTEENTH_INCH to be an integer
... # [...]
... SIXTEENTH_INCH = 3 # 1/16″ is 1.5mm
... INCH = 16 * SIXTEENTH_INCH
Although it would probably be easier to make the unitary value 0.1mm:
>>> class Distance(QuantityUnit):
... MILLIMETERS = 10
... # [...]
... SIXTEENTH_INCH = 15
... INCH = 16 * SIXTEENTH_INCH
In full:
>>> class Distance(QuantityUnit):
... MILLIMETERS = 10
... CENTIMETERS = 10 * MILLIMETERS
... METERS = 100 * CENTIMETERS
... KILOMETERS = 1000 * METERS
... SIXTEENTH_INCH = 15
... INCH = 16 * SIXTEENTH_INCH
... HALF_INCH = 8 * SIXTEENTH_INCH
... QUARTER_INCH = 4 * SIXTEENTH_INCH
Creating Physical Quantities
----------------------------
A physical quantity can be created using the matrix multiplication operator "@" with a
quantity unit, e.g. 2 seconds:
>>> quantity: Quantity[Time] = 2 @ Time.SECONDS
Quantities of the same type relate to one another as you would expect (parentheses for
clarity):
>>> assert (2 @ Time.SECONDS) == (2000 @ Time.MILLISECONDS)
Note that quantities are really just integers which, at runtime, have no additional
information attached to them. This means that Python will happily accept any `Quantity`
wherever it would accept an integer; however static type checkers such as MyPy will complain
about it, which is good as it is almost certainly a mistake to attempt to, for example, sum
time and distance quantities, or sum a quantity with an arbitrary value:
>>> meaningless_value = (2 @ Time.SECONDS) + (10 @ Distance.MILLIMETERS)
>>> # Depending on the declaration of Distance, 100 here could be interpreted by the
>>> # runtime as 100m, 100cm, 100/24″, or anything else...
>>> unreliable_value = (2 @ Distance.METERS) + 100
Multiplying quantities with other quantities, even of the same type, would produce
a different unit, which is not supported. (However, it is conceivable that it could
be supported in the future.) The following will also fail static type checks:
>>> area = (2 @ Distance.METERS) * (2 @ Distance.METERS) # 4.0m²
>>> speed = (100 @ Distance.METERS) / (1 @ Time.SECONDS) # 100m/s
Using Physical Quantities
-------------------------
At some point quantities will need to be passed through an interface of some sort where the
unit information will be lost. Such interfaces will define a single unit they accept; for
instance `time.sleep()` requires an argument in seconds. Upon reaching such an interface,
quantities can be stripped of their scalar types and converted to the required unit with the
right bit-shift operator ">>" or floor division operator "//":
>>> delay = 2 @ Time.MINUTES
>>> # [...]
>>> import time
>>> time.sleep(delay >> Time.SECONDS)
With the ">>" operator the type of the resulting value is always a `float` and
will only be precise up to the highest precision unit for a defined `QuantityUnit` type (the
unit with a magnitude of `1`, which need not be explicitly defined).
With the "//" operator the resulting type will be `int`, with whatever loss of precision
that implies.
>>> delay = 3600 @ Time.MILLISECONDS
>>> # [...]
>>> time.sleep(delay // Time.SECONDS) # Will sleep for 3 seconds
Operations on Quantities
------------------------
At runtime all quantities are a subclass of integers, so all operations that work on
integers will work[^*] however type checkers only allow a subset of operations with certain
types.
[^*]: One small difference is multiplication by floats and division by float or int, which
would normally return floats, returns a new integer quantity. However division by
a quantity returns a float. Don't worry too much about this.
Quantities may be added to or subtracted from other quantities with the same unit, returning
a new quantity of that unit:
>>> assert (2 @ Time.SECONDS) + (500 @ Time.MILLISECONDS) == (2500 @ Time.MILLISECONDS)
They may be scaled by multiplying (*) and dividing (/) by unitless numeric values _only_,
resulting in a new quantity of the same unit. Note however that when scaling down there
will probably be some rounding loss depending on the precision of the unit.
>>> assert (2 @ Time.SECONDS) * 2 == (4 @ Time.SECONDS)
>>> assert (2 @ Time.SECONDS) / 2 == (1 @ Time.SECONDS)
>>> assert (2 @ Time.SECONDS) / 3 == (666 @ Time.MILLISECONDS) # Rounded down to whole milliseconds
In addition you may use _floor_ division (//) on quantities with another quantity of the
same unit to calculate how many times it can be divided into that size. Note when using
single units this is equivalent to converting to an untyped value of those units, so this is
the same as using the floor division operator with a unit value.
>>> assert (10 @ Time.SECONDS) // (2 @ Time.SECONDS) == 5
>>> assert (10 @ Time.SECONDS) // (1 @ Time.SECONDS) == 10
>>> assert (10 @ Time.SECONDS) // Time.SECONDS == 10 # Unit may be used as a convenience
To find the remainder after floor division, the modulus operator (%) returns a new quantity:
>>> assert (10 @ Time.SECONDS) % (3 @ Time.SECONDS) == (1 @ Time.SECONDS)
>>> assert (3.6 @ Time.SECONDS) % Time.SECONDS == (600 @ Time.MILLISECONDS)
This pairs well with the shift and floor division operators to get the modulus values as
floats or ints of a particular unit:
>>> assert (3.6 @ Time.SECONDS) % Time.SECONDS >> Time.SECONDS == 0.6
>>> assert (3.6 @ Time.SECONDS) % Time.SECONDS // Time.MILLISECONDS == 600
Choice of Operators
-------------------
The operators for constructing ("@") and deconstructing (">>") quantities may seem a bit
odd, given that what they actually do is multiply and divide the values. They were chosen to
be visually distinct from other multiplication and division operations on quantities and
scalar units.
The matrix multiplication operator therefore replaces the scalar multiplication operator,
while the shift operator, which looks arrow-like, is used to convert to the indicated unit.
i.e.:
>>> # quantity (converted to) units
>>> delay >> Time.SECONDS
3.6
"""
from __future__ import annotations
import enum
from typing import TYPE_CHECKING
from typing import Generic
from typing import Self
from typing import TypeVar
from typing import overload
U = TypeVar("U", bound="QuantityUnit")
if TYPE_CHECKING:
class Quantity(Generic[U]):
"""
A physical quantity of a given unit type 'U'
"""
def __init__(self, value: int|float|Quantity[U], /) -> None: ...
# Adding two quantities creates a new quantity
def __add__(self, other: Quantity[U], /) -> Quantity[U]: ...
# Subtracting a quantity from another creates a new quantity
def __sub__(self, other: Quantity[U], /) -> Quantity[U]: ...
# Quantities can be multiplied by unitless values to produce a new quantity
def __mul__(self, other: int|float, /) -> Quantity[U]: ...
# Quantities can be divided by unitless values to produce a new quantity
def __truediv__(self, other: int|float, /) -> Quantity[U]: ...
# Quantities can be divided by (into) quantities of the same unit to produce
# a unitless value (the number of whole divisions of the quantity)
def __floordiv__(self, other: Quantity[U], /) -> int: ...
# The remainder of a floor division with another quantity
def __mod__(self, other: Quantity[U], /) -> Quantity[U]: ...
else:
# Although the runtime implementation does not use TypeVars, it is still generic to
# allow type subscripting.
class Quantity(int, Generic[U]):
"""
A physical quantity of a given unit type 'U'
"""
def __mul__(self, other: int|float, /) -> Quantity:
return Quantity(other.__rmul__(self))
def __truediv__(self, other: int|float, /) -> Quantity:
if isinstance(other, Quantity):
return super().__truediv__(other)
return Quantity(other.__rtruediv__(self))
class QuantityUnit(enum.Enum):
"""
Enum base class for units
"""
if TYPE_CHECKING:
@property
def value(self) -> int: ... # noqa: D102
def __rmatmul__(self, scalar: float|int) -> Quantity[Self]:
return Quantity(self.value * scalar)
def __rrshift__(self, quantity: Quantity[Self]) -> float:
return self.value.__rtruediv__(quantity) # type: ignore[operator]
def __rfloordiv__(self, quantity: Quantity[Self]) -> int:
return quantity // self.value # type: ignore[operator,no-any-return]
def __rmod__(self, quantity: Quantity[Self]) -> Quantity[Self]:
return Quantity(quantity % self.value) # type: ignore[operator]
[build-system]
requires = ["flit_core ~=3.8"]
build-backend = "flit_core.buildapi"
[[project.authors]]
name = "Dom Sekotill"
email = "dom.sekotill@kodo.org.uk"
[project]
name = "kodo.quantities"
version = "0.1.0"
description = "Types for representing physical quantities, which have a magnitude and a unit"
license = {file = "LICENCE.txt"}
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Typing :: Typed",
]
requires-python = "~=3.11"
[project.urls]
Source = "https://code.kodo.org.uk/dom/python-quantities"
Issues = "https://code.kodo.org.uk/dom/python-quantities/-/issues"
[tool.isort]
force_single_line = true
line_length = 92
[tool.unimport]
ignore-init = true
[tool.mypy]
strict = true
namespace_packages = true
explicit_package_bases = true
warn_unused_configs = true
warn_unreachable = true
"""
Tests for quantities
"""
from typing import TYPE_CHECKING
from kodo.quantities import QuantityUnit
class Time(QuantityUnit):
MS = 10
S = 1000 * MS
def test_add() -> None:
assert (1500 @ Time.MS) + (500 @ Time.MS) == (2000 @ Time.MS)
assert (1500 @ Time.MS) - (500 @ Time.MS) == (1000 @ Time.MS)
def test_multiplication() -> None:
assert (1800 @ Time.MS) * 2 == (3600 @ Time.MS)
assert (3600 @ Time.MS) * 0.5 == (1800 @ Time.MS)
assert (3600 @ Time.MS) / 2 == (1800 @ Time.MS)
assert (1800 @ Time.MS) / 0.5 == (3600 @ Time.MS)
def test_division_by_quantity() -> None:
assert (3600 @ Time.MS) // (1 @ Time.S) == 3
assert isinstance((3 @ Time.S) // (1 @ Time.S), int)
assert (3600 @ Time.MS) // Time.S == 3
assert isinstance((3 @ Time.S) // Time.S, int)
def test_modulus() -> None:
assert (3600 @ Time.MS) % (2 @ Time.S) == 1600 @ Time.MS
assert (3600 @ Time.MS) % Time.S == 600 @ Time.MS
if TYPE_CHECKING:
def type_checks() -> None:
# Checks for type checker false negatives
#
# All the following should result in an error when checked with mypy or pyright; the
# errors are suppressed but if they are not raised the suppression itself will cause
# mypy to raise an error in strict mode.
_ = (1 @ Time.S) + 3 # type: ignore[operator]
_ = (1 @ Time.S) - 3.0 # type: ignore[operator]
_ = (1 @ Time.S) * (1 @ Time.S) # type: ignore[operator]
_ = (1 @ Time.S) / (1 @ Time.S) # type: ignore[operator]
_ = (1 @ Time.S) // 2 # type: ignore[operator]
_ = (1 @ Time.S) // 2.0 # type: ignore[operator]