Skip to content

Commit

Permalink
Bump ruff Python compat target to 3.10
Browse files Browse the repository at this point in the history
  • Loading branch information
inducer committed Nov 6, 2024
1 parent 7399504 commit c9dfd23
Show file tree
Hide file tree
Showing 21 changed files with 65 additions and 88 deletions.
6 changes: 3 additions & 3 deletions pymbolic/geometric_algebra/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
"""

from abc import ABC, abstractmethod
from collections.abc import Mapping
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import Any, Dict, Generic, Sequence, TypeVar, cast
from typing import Any, Generic, TypeVar, cast

import numpy as np

Expand Down Expand Up @@ -590,7 +590,7 @@ def __init__(
else:
new_data[bits] = new_coeff
else:
new_data = cast(Dict[int, CoeffT], data)
new_data = cast(dict[int, CoeffT], data)

# }}}

Expand Down
3 changes: 2 additions & 1 deletion pymbolic/geometric_algebra/primitives.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
# This is experimental, undocumented, and could go away any second.
# Consider yourself warned.

from typing import ClassVar, Hashable
from collections.abc import Hashable
from typing import ClassVar

from pymbolic.primitives import Expression, Variable, expr_dataclass
from pymbolic.typing import ExpressionT
Expand Down
11 changes: 1 addition & 10 deletions pymbolic/interop/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,19 +457,10 @@ def to_evaluatable_python_function(expr: ExpressionT,
def foo(*, E, S):
return S // 32 + E % 32
"""
import sys

from pymbolic.mapper.dependency import CachedDependencyMapper

if sys.version_info < (3, 9):
try:
from astunparse import unparse
except ImportError:
raise RuntimeError("'to_evaluate_python_function' needs"
"astunparse for Py<3.9. Install via `pip"
" install astunparse`") from None
else:
unparse = ast.unparse
unparse = ast.unparse

dep_mapper = CachedDependencyMapper(composite_leaves=True)
deps = sorted({dep.name for dep in dep_mapper(expr)})
Expand Down
6 changes: 3 additions & 3 deletions pymbolic/interop/matchpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,10 @@


import abc
from collections.abc import Callable, Iterable, Iterator, Mapping
from dataclasses import dataclass, field, fields
from functools import partial
from typing import Callable, ClassVar, Generic, Iterable, Iterator, Mapping, TypeVar
from typing import ClassVar, Generic, TypeAlias, TypeVar

from matchpy import (
Arity,
Expand All @@ -54,7 +55,6 @@
ReplacementRule,
Wildcard as BaseWildcard,
)
from typing_extensions import TypeAlias

import pymbolic.primitives as p
from pymbolic.typing import ScalarT
Expand Down Expand Up @@ -85,7 +85,7 @@ def head(self):

def __lt__(self, other):
# Used by matchpy internally to order subexpressions
if not isinstance(other, (Expression,)):
if not isinstance(other, Expression):
return NotImplemented
if type(other) is type(self):
if self.value == other.value:
Expand Down
3 changes: 2 additions & 1 deletion pymbolic/interop/matchpy/mapper.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

from typing import Any, Callable
from collections.abc import Callable
from typing import Any

from pymbolic.interop.matchpy import PymbolicOp

Expand Down
3 changes: 2 additions & 1 deletion pymbolic/interop/matchpy/tofrom.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import annotations

from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Callable
from typing import Any

import multiset
import numpy as np
Expand Down
28 changes: 13 additions & 15 deletions pymbolic/mapper/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,19 @@
"""

from abc import ABC, abstractmethod
from collections.abc import Mapping
from collections.abc import Callable, Hashable, Iterable, Mapping, Set
from typing import (
TYPE_CHECKING,
AbstractSet,
Callable,
Concatenate,
Generic,
Hashable,
Iterable,
TypeAlias,
TypeVar,
cast,
)
from warnings import warn

from immutabledict import immutabledict
from typing_extensions import Concatenate, ParamSpec, TypeAlias, TypeIs
from typing_extensions import ParamSpec, TypeIs

import pymbolic.primitives as p
from pymbolic.typing import ArithmeticExpressionT, ExpressionT
Expand Down Expand Up @@ -640,7 +638,7 @@ class CachedCombineMapper(CachedMapper, CombineMapper):
CollectedT = TypeVar("CollectedT")


class Collector(CombineMapper[AbstractSet[CollectedT], P]):
class Collector(CombineMapper[Set[CollectedT], P]):
"""A subclass of :class:`CombineMapper` for the common purpose of
collecting data derived from an expression in a set that gets 'unioned'
across children at each non-leaf node in the expression tree.
Expand All @@ -651,34 +649,34 @@ class Collector(CombineMapper[AbstractSet[CollectedT], P]):
"""

def combine(self,
values: Iterable[AbstractSet[CollectedT]]
) -> AbstractSet[CollectedT]:
values: Iterable[Set[CollectedT]]
) -> Set[CollectedT]:
import operator
from functools import reduce
return reduce(operator.or_, values, set())

def map_constant(self, expr: object,
*args: P.args, **kwargs: P.kwargs) -> AbstractSet[CollectedT]:
*args: P.args, **kwargs: P.kwargs) -> Set[CollectedT]:
return set()

def map_variable(self, expr: p.Variable,
*args: P.args, **kwargs: P.kwargs) -> AbstractSet[CollectedT]:
*args: P.args, **kwargs: P.kwargs) -> Set[CollectedT]:
return set()

def map_wildcard(self, expr: p.Wildcard,
*args: P.args, **kwargs: P.kwargs) -> AbstractSet[CollectedT]:
*args: P.args, **kwargs: P.kwargs) -> Set[CollectedT]:
return set()

def map_dot_wildcard(self, expr: p.DotWildcard,
*args: P.args, **kwargs: P.kwargs) -> AbstractSet[CollectedT]:
*args: P.args, **kwargs: P.kwargs) -> Set[CollectedT]:
return set()

def map_star_wildcard(self, expr: p.StarWildcard,
*args: P.args, **kwargs: P.kwargs) -> AbstractSet[CollectedT]:
*args: P.args, **kwargs: P.kwargs) -> Set[CollectedT]:
return set()

def map_function_symbol(self, expr: p.FunctionSymbol,
*args: P.args, **kwargs: P.kwargs) -> AbstractSet[CollectedT]:
*args: P.args, **kwargs: P.kwargs) -> Set[CollectedT]:
return set()


Expand Down
4 changes: 2 additions & 2 deletions pymbolic/mapper/coefficient.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
THE SOFTWARE.
"""

from collections.abc import Collection
from typing import Literal, Mapping, TypeAlias, cast
from collections.abc import Collection, Mapping
from typing import Literal, TypeAlias, cast

import pymbolic.primitives as p
from pymbolic.mapper import Mapper
Expand Down
11 changes: 6 additions & 5 deletions pymbolic/mapper/collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
THE SOFTWARE.
"""

from typing import AbstractSet, Sequence, cast
from collections.abc import Sequence, Set
from typing import cast

import pymbolic
import pymbolic.primitives as p
Expand All @@ -43,7 +44,7 @@ class TermCollector(IdentityMapper[[]]):
coefficients and are not used for term collection.
"""

def __init__(self, parameters: AbstractSet[p.AlgebraicLeaf] | None = None):
def __init__(self, parameters: Set[p.AlgebraicLeaf] | None = None):
if parameters is None:
parameters = set()
self.parameters = parameters
Expand All @@ -53,7 +54,7 @@ def get_dependencies(self, expr: ExpressionT) -> DependenciesT:
return DependencyMapper()(expr)

def split_term(self, mul_term: ExpressionT) -> tuple[
AbstractSet[tuple[ArithmeticExpressionT, ArithmeticExpressionT]],
Set[tuple[ArithmeticExpressionT, ArithmeticExpressionT]],
ArithmeticExpressionT
]:
"""Returns a pair consisting of:
Expand Down Expand Up @@ -81,7 +82,7 @@ def exponent(term: ExpressionT) -> ArithmeticExpressionT:

if isinstance(mul_term, Product):
terms: Sequence[ExpressionT] = mul_term.children
elif isinstance(mul_term, (Power, AlgebraicLeaf)):
elif isinstance(mul_term, Power | AlgebraicLeaf):
terms = [mul_term]
elif not bool(self.get_dependencies(mul_term)):
terms = [mul_term]
Expand Down Expand Up @@ -114,7 +115,7 @@ def exponent(term: ExpressionT) -> ArithmeticExpressionT:

def map_sum(self, expr: p.Sum) -> ExpressionT:
term2coeff: dict[
AbstractSet[tuple[ArithmeticExpressionT, ArithmeticExpressionT]],
Set[tuple[ArithmeticExpressionT, ArithmeticExpressionT]],
ArithmeticExpressionT] = {}
for child in expr.children:
term, coeff = self.split_term(child)
Expand Down
2 changes: 1 addition & 1 deletion pymbolic/mapper/constant_folder.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def fold(self,
assert is_arithmetic_expression(child)

if isinstance(child, klass):
assert isinstance(child, (Sum, Product))
assert isinstance(child, Sum | Product)
queue = list(child.children) + queue
else:
if self.is_constant(child):
Expand Down
7 changes: 3 additions & 4 deletions pymbolic/mapper/dependency.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,14 @@
THE SOFTWARE.
"""

from typing import AbstractSet

from typing_extensions import TypeAlias
from collections.abc import Set
from typing import TypeAlias

import pymbolic.primitives as p
from pymbolic.mapper import CachedMapper, Collector, CSECachingMapperMixin, P


DependenciesT: TypeAlias = AbstractSet[p.AlgebraicLeaf | p.CommonSubexpression]
DependenciesT: TypeAlias = Set[p.AlgebraicLeaf | p.CommonSubexpression]


class DependencyMapper(
Expand Down
2 changes: 1 addition & 1 deletion pymbolic/mapper/differentiator.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ def differentiate(expression,
variable,
func_mapper=map_math_functions_by_name,
allowed_nonsmoothness="none"):
if not isinstance(variable, (primitives.Variable, primitives.Subscript)):
if not isinstance(variable, primitives.Variable | primitives.Subscript):
variable = primitives.make_variable(variable)
from pymbolic import flatten
return flatten(DifferentiationMapper(
Expand Down
2 changes: 1 addition & 1 deletion pymbolic/mapper/optimize.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ def wrapper(cls: type) -> type:
if not name.startswith("__") or name == "__call__":
method = getattr(cls, name)
if (not callable(method)
or isinstance(method, (property, cached_property))):
or isinstance(method, property | cached_property)):
# properties don't have *args, **kwargs
continue

Expand Down
3 changes: 2 additions & 1 deletion pymbolic/mapper/substitutor.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from typing import Any, Callable
from collections.abc import Callable
from typing import Any

from useful_types import SupportsGetItem, SupportsItems

Expand Down
2 changes: 1 addition & 1 deletion pymbolic/mapper/unifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def treat_mismatch(self, expr, other, urecs):
raise NotImplementedError

def unification_record_from_equation(self, lhs, rhs):
if isinstance(lhs, (tuple, list)) or isinstance(rhs, (tuple, list)):
if isinstance(lhs, tuple | list) or isinstance(rhs, tuple | list):
# Always force lists/tuples to agree elementwise, never
# generate a unification record between them directly.
# This pushes the matching process down to the elementwise
Expand Down
10 changes: 5 additions & 5 deletions pymbolic/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@
THE SOFTWARE.
"""

from collections.abc import Sequence
from sys import intern
from typing import ClassVar, Sequence, Tuple, Union
from typing import ClassVar, TypeAlias

from immutabledict import immutabledict
from typing_extensions import TypeAlias

import pytools.lex
from pytools import memoize_method
Expand Down Expand Up @@ -128,7 +128,7 @@ def __hash__(self) -> int: # type: ignore[override]


LexTable: TypeAlias = Sequence[
Tuple[str, Union[pytools.lex.RE, Tuple[Union[str, pytools.lex.RE], ...]]]]
tuple[str, pytools.lex.RE | tuple[str | pytools.lex.RE, ...]]]


class Parser:
Expand Down Expand Up @@ -500,15 +500,15 @@ def parse_postfix(self, pstate, min_precedence, left_exp):

pstate.advance()
if pstate.is_at_end() or pstate.next_tag() is _closepar:
if isinstance(left_exp, (tuple, list)) \
if isinstance(left_exp, tuple | list) \
and not isinstance(left_exp, FinalizedContainer):
# left_expr is a container with trailing commas
pass
else:
left_exp = (left_exp,)
else:
new_el = self.parse_expression(pstate, _PREC_COMMA)
if isinstance(left_exp, (tuple, list)) \
if isinstance(left_exp, tuple | list) \
and not isinstance(left_exp, FinalizedContainer):
left_exp = (*left_exp, new_el)
else:
Expand Down
12 changes: 5 additions & 7 deletions pymbolic/primitives.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,23 @@
"""

import re
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass, fields
from sys import intern
from typing import (
TYPE_CHECKING,
Any,
Callable,
ClassVar,
Iterable,
Mapping,
NoReturn,
Protocol,
Type,
TypeAlias,
TypeVar,
cast,
)
from warnings import warn

from immutabledict import immutabledict
from typing_extensions import TypeAlias, TypeIs, dataclass_transform
from typing_extensions import TypeIs, dataclass_transform

from . import traits
from .typing import ArithmeticExpressionT, ExpressionT, NumberT, ScalarT
Expand Down Expand Up @@ -1042,7 +1040,7 @@ def {cls.__name__}_setstate(self, state):

# {{{ assign mapper_method

mm_cls = cast(Type[_HasMapperMethod], cls)
mm_cls = cast(type[_HasMapperMethod], cls)

snake_clsname = _CAMEL_TO_SNAKE_RE.sub("_", mm_cls.__name__).lower()
default_mapper_method_name = f"map_{snake_clsname}"
Expand Down Expand Up @@ -1916,7 +1914,7 @@ def is_zero(value: object) -> bool:


def wrap_in_cse(expr: ExpressionT, prefix=None) -> ExpressionT:
if isinstance(expr, (Variable, Subscript)):
if isinstance(expr, Variable | Subscript):
return expr

if isinstance(expr, CommonSubexpression):
Expand Down
2 changes: 1 addition & 1 deletion pymbolic/traits.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def traits(x):
try:
return x.traits()
except AttributeError:
if isinstance(x, (complex, float)):
if isinstance(x, complex | float):
return FieldTraits()
elif isinstance(x, int):
return IntegerTraits()
Expand Down
Loading

0 comments on commit c9dfd23

Please sign in to comment.