Skip to content

Commit

Permalink
ci: buff out the ruff edges
Browse files Browse the repository at this point in the history
Signed-off-by: nstarman <nstarman@users.noreply.github.com>
  • Loading branch information
nstarman committed Apr 27, 2024
1 parent e4c4e15 commit 67e38ea
Show file tree
Hide file tree
Showing 33 changed files with 161 additions and 173 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/formatting_check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ jobs:
with:
python-version: "3.9"

- uses: pre-commit/action@v3.0.0
- uses: pre-commit/action@v3.0.0
3 changes: 1 addition & 2 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install --upgrade build twine
python -m pip install --upgrade build twine
- name: Build and publish
env:
Expand All @@ -37,4 +37,3 @@ jobs:
run: |
python -m build
twine upload dist/*
42 changes: 32 additions & 10 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,17 +1,39 @@
ci:
autoupdate_commit_msg: "chore: update pre-commit hooks"
autofix_commit_msg: "style: pre-commit fixes"

default_language_version:
python: python3.9
python: python3.9

repos:
- repo: https://github.com/psf/black
rev: 23.9.0
- repo: meta
hooks:
- id: black
- repo: https://github.com/pycqa/isort
rev: 5.12.0
- id: check-useless-excludes

- repo: https://github.com/abravalheri/validate-pyproject
rev: v0.16
hooks:
- id: isort
args: ["--profile", "black"]
- id: validate-pyproject

- 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-yaml
- id: debug-statements
- id: end-of-file-fixer
- id: mixed-line-ending
- id: trailing-whitespace

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.0
rev: "v0.4.1"
hooks:
# Run the linter
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
types_or: [python, pyi]
args: ["--fix", "--show-fixes"]
# Run the formatter
- id: ruff-format
types_or: [python, pyi]
18 changes: 9 additions & 9 deletions benchmark.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from typing import Tuple

import numpy as np
from tests.util import benchmark

from plum import Dispatcher, dispatch
from tests.util import benchmark


def f(x):
Expand All @@ -25,8 +25,8 @@ def g(x: str):
factor = int(np.round(dur_plum / dur_native))

print("# Function Calls")
print("Native call: {:6.2f} us ({:.1f} x)".format(dur_native, 1))
print("Plum call: {:6.2f} us ({:.1f} x)".format(dur_plum, factor))
print(f"Native call: {dur_native:6.2f} us ({1:.1f} x)")
print(f"Plum call: {dur_plum:6.2f} us ({factor:.1f} x)")
print()


Expand All @@ -49,8 +49,8 @@ def g2(x: Tuple[str]):
factor = int(np.round(dur_plum / dur_native))

print("# Parametric Function Calls")
print("Native call: {:6.2f} us ({:.1f} x)".format(dur_native, 1))
print("Plum call: {:6.2f} us ({:.1f} x)".format(dur_plum, factor))
print(f"Native call: {dur_native:6.2f} us ({1:.1f} x)")
print(f"Plum call: {dur_plum:6.2f} us ({factor:.1f} x)")
print()


Expand Down Expand Up @@ -90,14 +90,14 @@ def go(self, x: str):
factor = int(np.round(dur_plum / dur_native))

print("# Class Calls")
print("Native call: {:6.2f} us ({:.1f} x)".format(dur_native, 1))
print("Plum call: {:6.2f} us ({:.1f} x)".format(dur_plum, factor))
print(f"Native call: {dur_native:6.2f} us ({1:.1f} x)")
print(f"Plum call: {dur_plum:6.2f} us ({factor:.1f} x)")
print()

dur_native = benchmark(lambda x: a.go(x), (1,), n=1000, burn=10)
dur_plum = benchmark(lambda x: b.go(x), (1,), n=1000, burn=10)
factor = int(np.round(dur_plum / dur_native))

print("# Class Attribute Calls")
print("Native call: {:6.2f} us ({:.1f} x)".format(dur_native, 1))
print("Plum call: {:6.2f} us ({:.1f} x)".format(dur_plum, factor))
print(f"Native call: {dur_native:6.2f} us ({1:.1f} x)")
print(f"Plum call: {dur_plum:6.2f} us ({factor:.1f} x)")
2 changes: 1 addition & 1 deletion check_linter_assertions.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def parse_assertions(source_dir: Path, linter: str) -> FileLineInfo:
asserted_errors: FileLineInfo = defaultdict(lambda: defaultdict(list))

for path in source_dir.resolve().rglob("*.py"): # Important to `resolve` here!
with open(path, "r") as f:
with open(path) as f:
lines = f.read().splitlines()
for i, line in enumerate(lines):
# Check if the line has an error assertion.
Expand Down
8 changes: 4 additions & 4 deletions docs/basic_usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ from plum import dispatch
@dispatch
def f(x: str):
return "This is a string!"


@dispatch
def f(x: int):
Expand Down Expand Up @@ -64,11 +64,11 @@ For a function `f`, all available methods can be obtained with `f.methods`:
```python
>>> f.methods
List of 3 method(s):
[0] f(x: str)
[0] f(x: str)
<function f at ...> @ ...
[1] f(x: int)
[1] f(x: int)
<function f at ...> @ ...
[2] f(x: numbers.Number)
[2] f(x: numbers.Number)
<function f at ...> @ ...
```

Expand Down
2 changes: 1 addition & 1 deletion docs/classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class Real:
@dispatch
def __add__(self, other: int):
return "int added"

@dispatch
def __add__(self, other: float):
return "float added"
Expand Down
6 changes: 3 additions & 3 deletions docs/comparison.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ from multipledispatch import dispatch
@dispatch((int, Number), int)
def f(x, y):
return "first"


@dispatch(int, Number)
def f(x, y):
Expand Down Expand Up @@ -121,7 +121,7 @@ from multipledispatch import dispatch
class A:
def f(self, x):
return "fallback"


class B(A):
@dispatch(int)
Expand All @@ -148,7 +148,7 @@ from multimethod import multimethod
class A:
def f(self, x):
return "fallback"


class B(A):
@multimethod
Expand Down
12 changes: 6 additions & 6 deletions docs/conversion_promotion.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

## Return Types

When a return type is not matched, Plum will attempt to convert the result to the
When a return type is not matched, Plum will attempt to convert the result to the
right type.

% clear-namespace
Expand Down Expand Up @@ -76,7 +76,7 @@ Let us implement that conversion:
from operator import truediv

from plum import conversion_method


@conversion_method(type_from=Rational, type_to=Number)
def rational_to_number(q):
Expand Down Expand Up @@ -112,13 +112,13 @@ from plum import dispatch, promote, add_promotion_rule, add_conversion_method
@dispatch
def add(x, y):
return add(*promote(x, y))


@dispatch
def add(x: int, y: int):
return x + y


@dispatch
def add(x: float, y: float):
return x + y
Expand Down
4 changes: 2 additions & 2 deletions docs/dispatch.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ from plum import dispatch
@dispatch
def f(x: int):
return "int"


@dispatch
def f(x: str):
return "str"
Expand Down
2 changes: 1 addition & 1 deletion docs/integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def do(x: str) -> str:
def do(x):
# Final method without an implementation. This scans for all `overload`-decorated
# methods and properly adds them as Plum methods.
pass
pass


@overload
Expand Down
15 changes: 7 additions & 8 deletions docs/parametric.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@ You can use parametric types to perform dispatch:
@dispatch
def f(x: A):
return "Just some A"


@dispatch
def f(x: A[int]):
return "A has an integer!"


@dispatch
def f(x: A[float]):
return "A has a float!"
Expand Down Expand Up @@ -136,7 +136,7 @@ class NTuple:
n = len(args)
# For simplicity, take the type of the first argument! We could do something
# more refined here.
t = type(args[0])
t = type(args[0])
return n, t

@classmethod
Expand Down Expand Up @@ -193,10 +193,10 @@ Finally, it implements the desired covariance:
>>> issubclass(NTuple[2, int], NTuple[2, Number])
True

>>> issubclass(NTuple[2, int], NTuple[2, float])
>>> issubclass(NTuple[2, int], NTuple[2, float])
False

>>> issubclass(NTuple[2, int], NTuple[3, int])
>>> issubclass(NTuple[2, int], NTuple[3, int])
False
```

Expand Down Expand Up @@ -279,4 +279,3 @@ Those are Python 3.7 and below, but Plum does not support those versions.

## Example: `NDArray`
See [here](comparison-parametric).

6 changes: 3 additions & 3 deletions docs/precedence.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def mul_no_precedence(a: ZeroElement, b: Element):
@dispatch
def mul_no_precedence(a: Element, b: SpecialisedElement):
return "specialised operation"


@dispatch(precedence=1)
def mul(a: ZeroElement, b: Element):
Expand All @@ -58,11 +58,11 @@ def mul(a: Element, b: SpecialisedElement):

>>> try: mul_no_precedence(zero, specialised_element)
... except Exception as e: print(f"{type(e).__name__}: {e}")
AmbiguousLookupError: `mul_no_precedence(<ZeroElement object at ...>, <SpecialisedElement
AmbiguousLookupError: `mul_no_precedence(<ZeroElement object at ...>, <SpecialisedElement
object at ...>)` is ambiguous.
Candidates:
mul_no_precedence(a: ZeroElement, b: Element)
<function mul_no_precedence at ...> @ ...md:26
<function mul_no_precedence at ...> @ ...md:26
mul_no_precedence(a: Element, b: SpecialisedElement)
<function mul_no_precedence at ...> @ ...

Expand Down
2 changes: 1 addition & 1 deletion docs/references.bib
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
---
---
---
10 changes: 5 additions & 5 deletions docs/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ isinstance(x, t) == issubclass(type(x), t)
For example, `int` is faithful, since `type(1) == int`;
but `Literal[1]` is not faithful, since `issubclass(int, Literal[1])` is false.

Methods which have signatures that depend only on faithful types will
Methods which have signatures that depend only on faithful types will
be performant.
On the other hand, methods which have one or more signatures with one or more
unfaithful types cannot use caching and will therefore be less performant.
Expand Down Expand Up @@ -172,8 +172,8 @@ NotFoundLookupError: `f(1)` could not be resolved...

>>> g.methods
List of 1 method(s):
[0] f(x:
plum.type.ModuleType[tensorflow.python.framework.ops.EagerTensor])
[0] f(x:
plum.type.ModuleType[tensorflow.python.framework.ops.EagerTensor])
<function f at ...> @ ...

>>> import tensorflow as tf # Very slow...
Expand Down Expand Up @@ -224,12 +224,12 @@ def f(x: ProxyInt):
return "An integer!"

# Deliver the type that `ProxyInt` should point to. Do this before `f` is first used!
ProxyInt.deliver(int)
ProxyInt.deliver(int)
```

```python
>>> f(1)
'An integer!'
'An integer!'
```

Like for `PromisedType`,
Expand Down
2 changes: 1 addition & 1 deletion docs/union_aliases.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ Hurray!
Note that the documentation prints `Union[Scalar]` rather than just `Scalar`.
This is intentional: it is to prevent breaking code that depends on how unions
print.
For example, printing just `Scalar` would omit the type parameter(s).
For example, printing just `Scalar` would omit the type parameter(s).

Let's see with a few more examples how this works:

Expand Down
11 changes: 4 additions & 7 deletions plum/alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,12 @@ def _new_repr(self):
# element, the positions of following insertions need to be appropriately
# incremented.
args = list(args)
delta = 0
# Sort by insertion position to ensure that all following insertions are at higher
# indices. This makes the bookkeeping simple.
for i, alias in sorted(zip(found_positions, found_aliases), key=lambda x: x[0]):
for delta, (i, alias) in enumerate(
sorted(zip(found_positions, found_aliases), key=lambda x: x[0])
):
args.insert(i + delta, alias)
delta += 1

# Filter all elements of unions that are aliased.
new_args = ()
Expand Down Expand Up @@ -152,10 +152,7 @@ def set_union_alias(union, alias):
Returns:
type or type hint: `union`.
"""
if not isinstance(union, _union_type):
args = (union,)
else:
args = get_args(union)
args = get_args(union) if isinstance(union, _union_type) else (union,)
for existing_union, existing_alias in _aliased_unions:
if set(existing_union) == set(args) and alias != existing_alias:
if isinstance(union, _union_type):
Expand Down

0 comments on commit 67e38ea

Please sign in to comment.