generated from peaky76/python-poetry-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from peaky76/develop
Develop
- Loading branch information
Showing
21 changed files
with
671 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
repos: | ||
- repo: local | ||
hooks: | ||
- id: ruff-format | ||
name: Run ruff format | ||
entry: bash -c 'poetry run ruff format . --preview && git add .' | ||
language: system | ||
files: '\.py$' | ||
- id: sphinx-build | ||
name: Build Sphinx docs | ||
entry: bash -c 'poetry run sphinx-build -b html docs/source docs/build' | ||
language: system | ||
files: 'docs/source/.*\.rst$' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
# Changelog | ||
|
||
## 1.0.0 (2024-02-14) | ||
|
||
#### New Features | ||
|
||
- `LikenessMixin` class | ||
- `discount` function | ||
- `ignore` function | ||
- `likeness` function | ||
|
||
#### Docs | ||
|
||
- Added and built in sphinx-rtd style | ||
|
||
#### Others | ||
|
||
- Set as py.typed |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
# Minimal makefile for Sphinx documentation | ||
# | ||
|
||
# You can set these variables from the command line, and also | ||
# from the environment for the first two. | ||
SPHINXOPTS ?= | ||
SPHINXBUILD ?= sphinx-build | ||
SOURCEDIR = source | ||
BUILDDIR = build | ||
|
||
# Put it first so that "make" without argument is like "make help". | ||
help: | ||
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) | ||
|
||
.PHONY: help Makefile | ||
|
||
# Catch-all target: route all unknown targets to Sphinx using the new | ||
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). | ||
%: Makefile | ||
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,3 @@ | ||
# python-poetry-template | ||
# likeness | ||
|
||
A template for python projects using poetry as package manager. | ||
Includes dependabot and basic ci with linting, typing and testing. | ||
A mixin that puts a number on object comparisons. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
API | ||
=== | ||
|
||
.. automodule:: likeness.likeness_mixin | ||
:members: | ||
|
||
.. automodule:: likeness.discount | ||
:members: | ||
|
||
.. automodule:: likeness.ignore | ||
:members: | ||
|
||
.. automodule:: likeness.likeness | ||
:members: |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
# Configuration file for the Sphinx documentation builder. | ||
# | ||
# For the full list of built-in configuration values, see the documentation: | ||
# https://www.sphinx-doc.org/en/master/usage/configuration.html | ||
|
||
# -- Project information ----------------------------------------------------- | ||
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information | ||
|
||
project = "likeness" | ||
copyright = "2024, Robert Peacock" | ||
author = "Robert Peacock" | ||
|
||
# -- General configuration --------------------------------------------------- | ||
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration | ||
|
||
extensions = ["sphinx.ext.autodoc", "sphinx_rtd_theme"] | ||
|
||
templates_path = ["_templates"] | ||
exclude_patterns = [] | ||
|
||
|
||
# -- Options for HTML output ------------------------------------------------- | ||
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output | ||
|
||
html_theme = "sphinx_rtd_theme" | ||
html_static_path = ["_static"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
.. likeness documentation master file, created by | ||
sphinx-quickstart on Wed Feb 14 22:08:53 2024. | ||
You can adapt this file completely to your liking, but it should at least | ||
contain the root `toctree` directive. | ||
likeness | ||
======== | ||
|
||
You want to compare two instances of a class. But standard comparison with ``=``, ``>`` and ``<`` don't achieve what you need. | ||
What you'd like is a numeric value to represent how similar one instance is to another, based on the instance's attributes. | ||
This is what ``likeness`` does. Via a few simple steps, you can compare instances of the same class like this: | ||
|
||
.. code-block:: python | ||
a.like(b) | ||
and get a float value ``0 < x < 1`` in return | ||
|
||
Quickstart | ||
========== | ||
|
||
To make a class comparable in this way, first make it inherit from ``likeness.LikenessMixin``. | ||
|
||
Then, define a class variable ``_likeness_functions``. This should be a dictionary, where the keys are the names of instance attributes, | ||
and the values are callables analysing those attributes. Each callable should return a float between 0 and 1. And that's it. | ||
|
||
You can then compare two objects of this class by calling the ``like`` method on one of them, passing the other as an argument. | ||
The ``LikenessMixin`` will evaluate each of the ``_likeness_functions`` and return the product. | ||
|
||
Example | ||
======= | ||
|
||
.. code-block:: python | ||
import operator | ||
from likeness import ignore, LikenessMixin | ||
class Person(LikenessMixin): | ||
_likeness_functions = { | ||
'name': ignore, | ||
'sex': operator.eq, | ||
'age': lambda x, y: 1 - abs(x - y) / 100 | ||
} | ||
def __init__(self, *, name, sex, age): | ||
self.name = name | ||
self.sex = sex | ||
self.age = age | ||
a = Person(name='Alice', sex='F', age=40) | ||
b = Person(name='Betty', sex='F', age=90) | ||
The ``Person`` class is now comparable. ``a.like(b)`` will be calculated as follows: | ||
|
||
- ``ignore`` is a simple utility function to indicate you want to ignore this attribute. It always returns 1 so has no effect on output. You don't need to use it, but is a convenient way to self-document. | ||
- ``operator.eq`` is the built-in function that returns 1 if the two values are equal, 0 otherwise, so in this case will also return 1. | ||
- for ``age``, we are using a lambda. This needs two arguments and returns a float between 0 and 1. In this case, it returns 0.5. | ||
|
||
Therefore, ``a.like(b)`` will return 1 * 1 * 0.5 = 0.5. | ||
|
||
Other utilities | ||
=============== | ||
|
||
You have seen ``ignore`` already. There are a few other convenience utilities provided: | ||
|
||
- ``discount`` - this makes calculations like the one used in ``age`` slightly more convenient. You specify the discount factor which will take the likeness down from 1 to 0. In this case we could replace our lambda with ``discount( abs(x - y) / 100)``. | ||
|
||
- ``likeness`` - if one of your attributes is of a type that itself is comparable, you can use this to compare the two instances. | ||
For example, if ``Person`` had a ``mother`` attribute, you could use ``likeness`` to compare the two mothers, instead of having to use ``lambda x, y: x.like(y)`` | ||
|
||
Further info | ||
============ | ||
|
||
See :doc:`api` for more information. | ||
|
||
.. toctree:: | ||
:maxdepth: 2 | ||
:caption: Contents: | ||
|
||
Home <self> | ||
api | ||
|
||
Indices | ||
======= | ||
|
||
* :ref:`genindex` | ||
* :ref:`modindex` | ||
* :ref:`search` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
from .discount import discount | ||
from .ignore import ignore | ||
from .likeness import likeness | ||
from .likeness_mixin import LikenessMixin | ||
|
||
__all__ = ["LikenessMixin", "discount", "ignore", "likeness"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
def discount(calculation: float) -> float: | ||
""" | ||
Calculate the discounted value. | ||
:param calculation: The original value to be discounted. | ||
:type calculation: float | ||
:raises ValueError: If the calculation is less than 0. | ||
:return: The discounted value. It is the maximum of 1 minus the calculation and 0. | ||
:rtype: float | ||
""" | ||
if calculation < 0: | ||
raise ValueError("Discount function must return a value below 1") | ||
return max(1 - calculation, 0) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
def ignore(a: object, b: object) -> float: | ||
""" | ||
Ignores the input parameters and returns 1. A helper function to use in LikenessMixin if you don't want a comparison to take place for a certain attribute. | ||
:param a: The first input parameter. This parameter is ignored. | ||
:type a: object | ||
:param b: The second input parameter. This parameter is ignored. | ||
:type b: object | ||
:return: The function always returns 1. | ||
:rtype: float | ||
""" | ||
return 1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
from .likeness_mixin import LikenessMixin | ||
|
||
|
||
def likeness(a: LikenessMixin, b: LikenessMixin) -> float: | ||
""" | ||
Calculate the likeness between two objects of type LikenessMixin. | ||
:param a: The first object to compare. | ||
:type a: LikenessMixin | ||
:param b: The second object to compare. | ||
:type b: LikenessMixin | ||
:return: The likeness between the two objects, calculated by calling the `like` method of the first object with the second object as the argument. | ||
:rtype: float | ||
""" | ||
return a.like(b) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
from typing import Callable, ClassVar, Self | ||
|
||
from numpy import array, prod | ||
|
||
|
||
class LikenessMixin: | ||
""" | ||
A mixin class that provides a method to calculate the likeness between two objects. | ||
:cvar _likeness_functions: A dictionary mapping attribute names to functions that calculate likeness. | ||
:vartype _likeness_functions: ClassVar[dict[str, Callable]] | ||
""" | ||
|
||
_likeness_functions: ClassVar[dict[str, Callable]] = {} | ||
|
||
def __init__(self, *args, **kwargs): | ||
""" | ||
Initialize the mixin, forwarding all unused arguments to the superclass. | ||
:param args: Positional arguments to be forwarded. | ||
:param kwargs: Keyword arguments to be forwarded. | ||
""" | ||
super().__init__(*args, **kwargs) # forwards all unused arguments | ||
|
||
def like(self, other: Self) -> float: | ||
""" | ||
Calculate the likeness between this object and another. | ||
The likeness is calculated as the product of the likeness base and the likeness factors. | ||
The likeness base is 1 if there are likeness functions defined or if this object is equal to the other. | ||
The likeness factors are calculated by applying the likeness functions to corresponding attributes of the two objects. | ||
:param other: The other object to compare with. | ||
:type other: Self | ||
:return: The likeness between this object and the other. | ||
:rtype: float | ||
:raises ValueError: If a likeness function fails to apply. | ||
""" | ||
likeness_base = float(bool(len(self._likeness_functions)) or self == other) | ||
|
||
factors = [] | ||
for attribute, function in self._likeness_functions.items(): | ||
try: | ||
a = getattr(self, attribute) | ||
b = getattr(other, attribute) | ||
factors.append(function(a, b)) | ||
except Exception: # noqa: PERF203 | ||
raise ValueError( | ||
f"Unable to calculate likeness: {attribute} comparison failed" | ||
) | ||
|
||
return prod(array([likeness_base, *factors])) |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
@ECHO OFF | ||
|
||
pushd %~dp0 | ||
|
||
REM Command file for Sphinx documentation | ||
|
||
if "%SPHINXBUILD%" == "" ( | ||
set SPHINXBUILD=sphinx-build | ||
) | ||
set SOURCEDIR=source | ||
set BUILDDIR=build | ||
|
||
%SPHINXBUILD% >NUL 2>NUL | ||
if errorlevel 9009 ( | ||
echo. | ||
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx | ||
echo.installed, then set the SPHINXBUILD environment variable to point | ||
echo.to the full path of the 'sphinx-build' executable. Alternatively you | ||
echo.may add the Sphinx directory to PATH. | ||
echo. | ||
echo.If you don't have Sphinx installed, grab it from | ||
echo.https://www.sphinx-doc.org/ | ||
exit /b 1 | ||
) | ||
|
||
if "%1" == "" goto help | ||
|
||
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% | ||
goto end | ||
|
||
:help | ||
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% | ||
|
||
:end | ||
popd |
Oops, something went wrong.