Skip to content

Commit

Permalink
Merge pull request #833 from gaphor/modernize-typing
Browse files Browse the repository at this point in the history
Replace old types info with 3.10+ constructs
  • Loading branch information
amolenaar authored Aug 20, 2024
2 parents 9a673fd + 5611fc0 commit 7b27506
Show file tree
Hide file tree
Showing 22 changed files with 130 additions and 116 deletions.
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
from typing import Dict
from __future__ import annotations

# -- Project information -----------------------------------------------------

Expand Down Expand Up @@ -111,7 +111,7 @@

# -- Options for LaTeX output ------------------------------------------------

latex_elements: Dict[str, str] = {
latex_elements: dict[str, str] = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
Expand Down
28 changes: 15 additions & 13 deletions gaphas/connector.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from functools import singledispatch
from typing import Callable, Optional, Protocol
from typing import Callable, Protocol

from gaphas.connections import Connections
from gaphas.geometry import intersect_line_line
Expand All @@ -13,14 +15,14 @@

class ConnectionSinkType(Protocol):
item: Item
port: Optional[Port]
port: Port | None

def __init__(self, item: Item, distance: float = 10):
...

def glue(
self, pos: SupportsFloatPos, secondary_pos: Optional[SupportsFloatPos] = None
) -> Optional[Pos]:
self, pos: SupportsFloatPos, secondary_pos: SupportsFloatPos | None = None
) -> Pos | None:
...

def constraint(self, item: Item, handle: Handle) -> Constraint:
Expand All @@ -40,10 +42,10 @@ def __init__(self, item: Item, handle: Handle, connections: Connections):
def allow(self, sink):
return True

def secondary_handle(self) -> Optional[Handle]:
def secondary_handle(self) -> Handle | None:
return None

def glue(self, sink: ConnectionSinkType) -> Optional[Pos]:
def glue(self, sink: ConnectionSinkType) -> Pos | None:
"""Glue the Connector handle on the sink's port."""
handle = self.handle
item = self.item
Expand Down Expand Up @@ -80,7 +82,7 @@ def connect(self, sink: ConnectionSinkType) -> None:
def connect_handle(
self,
sink: ConnectionSinkType,
callback: Optional[Callable[[Item, Handle, Item, Port], None]] = None,
callback: Callable[[Item, Handle, Item, Port], None] | None = None,
) -> None:
"""Create constraint between handle of a line and port of connectable
item.
Expand Down Expand Up @@ -110,7 +112,7 @@ def disconnect(self) -> None:

@Connector.register(Line)
class LineConnector(ItemConnector):
def secondary_handle(self) -> Optional[Handle]:
def secondary_handle(self) -> Handle | None:
item = self.item
handle = self.handle
handles = item.handles()
Expand All @@ -131,11 +133,11 @@ class ItemConnectionSink:
def __init__(self, item: Item, distance: float = 10) -> None:
self.item = item
self.distance = distance
self.port: Optional[Port] = None
self.port: Port | None = None

def glue(
self, pos: SupportsFloatPos, secondary_pos: Optional[SupportsFloatPos] = None
) -> Optional[Pos]:
self, pos: SupportsFloatPos, secondary_pos: SupportsFloatPos | None = None
) -> Pos | None:
max_dist = self.distance
glue_pos = None
for p in self.item.ports():
Expand All @@ -161,8 +163,8 @@ def constraint(self, item: Item, handle: Handle) -> Constraint:
@ConnectionSink.register(Element)
class ElementConnectionSink(ItemConnectionSink):
def glue(
self, pos: SupportsFloatPos, secondary_pos: Optional[SupportsFloatPos] = None
) -> Optional[Pos]:
self, pos: SupportsFloatPos, secondary_pos: SupportsFloatPos | None = None
) -> Pos | None:
if glue_pos := super().glue(pos, secondary_pos):
return glue_pos

Expand Down
18 changes: 10 additions & 8 deletions gaphas/constraint.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,10 @@
class and implement `Constraint.solve_for(Variable)` method to update
a variable with appropriate value.
"""
from __future__ import annotations

import logging
import math
from typing import Optional, Tuple

from gaphas.position import Position
from gaphas.solver import BaseConstraint, Constraint
Expand All @@ -35,13 +36,14 @@ class and implement `Constraint.solve_for(Variable)` method to update


def constraint(
horizontal: Optional[Tuple[Position, Position]] = None,
vertical: Optional[Tuple[Position, Position]] = None,
left_of: Optional[Tuple[Position, Position]] = None,
above: Optional[Tuple[Position, Position]] = None,
line: Optional[Tuple[Position, Tuple[Position, Position]]] = None,
*,
horizontal: tuple[Position, Position] | None = None,
vertical: tuple[Position, Position] | None = None,
left_of: tuple[Position, Position] | None = None,
above: tuple[Position, Position] | None = None,
line: tuple[Position, tuple[Position, Position]] | None = None,
delta: float = 0.0,
align: Optional[float] = None,
align: float | None = None,
) -> Constraint:
"""Utility (factory) method to create item's internal constraint between
two positions or between a position and a line.
Expand All @@ -67,7 +69,7 @@ def constraint(
line=(p, l)
Keep position ``p`` on line ``l``.
"""
cc: Optional[Constraint]
cc: Constraint | None
if horizontal:
p1, p2 = horizontal
cc = EqualsConstraint(p1[1], p2[1], delta)
Expand Down
10 changes: 6 additions & 4 deletions gaphas/cursor.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from functools import singledispatch
from typing import Optional
from typing import Union

from gaphas.connector import Handle
from gaphas.item import Element, Item, Line
Expand All @@ -9,15 +11,15 @@


@singledispatch
def cursor(item: Optional[Item], handle: Optional[Handle], pos: Pos) -> str:
def cursor(item: Union[Item, None], handle: Union[Handle, None], pos: Pos) -> str:
return DEFAULT_CURSOR


ELEMENT_CURSORS = ("nw-resize", "ne-resize", "se-resize", "sw-resize")


@cursor.register
def element_hover(item: Element, handle: Optional[Handle], pos: Pos) -> str:
def element_hover(item: Element, handle: Union[Handle, None], pos: Pos) -> str:
if handle:
index = item.handles().index(handle)
return ELEMENT_CURSORS[index] if index < 4 else DEFAULT_CURSOR
Expand All @@ -28,5 +30,5 @@ def element_hover(item: Element, handle: Optional[Handle], pos: Pos) -> str:


@cursor.register
def line_hover(item: Line, handle: Optional[Handle], pos: Pos) -> str:
def line_hover(item: Line, handle: Union[Handle, None], pos: Pos) -> str:
return LINE_CURSOR if handle else DEFAULT_CURSOR
6 changes: 3 additions & 3 deletions gaphas/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
from __future__ import annotations

from math import sqrt
from typing import Iterator, Tuple
from collections.abc import Iterator

Point = Tuple[float, float] # x, y
Rect = Tuple[float, float, float, float] # x, y, width, height
Point = tuple[float, float] # x, y
Rect = tuple[float, float, float, float] # x, y, width, height


class Rectangle:
Expand Down
22 changes: 11 additions & 11 deletions gaphas/matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@

from __future__ import annotations

from typing import Callable, SupportsFloat, Tuple
from typing import Callable, SupportsFloat

import cairo

MatrixTuple = Tuple[float, float, float, float, float, float]
Matrixtuple = tuple[float, float, float, float, float, float]


class Matrix:
Expand All @@ -34,31 +34,31 @@ def __init__(
matrix: cairo.Matrix | None = None,
) -> None:
self._matrix = matrix or cairo.Matrix(xx, yx, xy, yy, x0, y0)
self._handlers: set[Callable[[Matrix, MatrixTuple], None]] = set()
self._handlers: set[Callable[[Matrix, Matrixtuple], None]] = set()

def add_handler(
self,
handler: Callable[[Matrix, MatrixTuple], None],
handler: Callable[[Matrix, Matrixtuple], None],
) -> None:
self._handlers.add(handler)

def remove_handler(
self,
handler: Callable[[Matrix, MatrixTuple], None],
handler: Callable[[Matrix, Matrixtuple], None],
) -> None:
self._handlers.discard(handler)

def notify(self, old: MatrixTuple) -> None:
def notify(self, old: Matrixtuple) -> None:
for handler in self._handlers:
handler(self, old)

def invert(self) -> None:
old: MatrixTuple = self.tuple()
old: Matrixtuple = self.tuple()
self._matrix.invert()
self.notify(old)

def rotate(self, radians: float) -> None:
old: MatrixTuple = self.tuple()
old: Matrixtuple = self.tuple()
self._matrix.rotate(radians)
self.notify(old)

Expand All @@ -68,7 +68,7 @@ def scale(self, sx: float, sy: float) -> None:
self.notify(old)

def translate(self, tx: float, ty: float) -> None:
old: MatrixTuple = self.tuple()
old: Matrixtuple = self.tuple()
self._matrix.translate(tx, ty)
self.notify(old)

Expand Down Expand Up @@ -116,7 +116,7 @@ def inverse(self) -> Matrix:
m.invert()
return m

def tuple(self) -> MatrixTuple:
def tuple(self) -> Matrixtuple:
return tuple(self) # type: ignore[arg-type, return-value]

def to_cairo(self) -> cairo.Matrix:
Expand All @@ -135,7 +135,7 @@ def __mul__(self, other: Matrix) -> Matrix:
return Matrix(matrix=self._matrix * other._matrix)

def __imul__(self, other: Matrix) -> Matrix:
old: MatrixTuple = self.tuple()
old: Matrixtuple = self.tuple()
self._matrix *= other._matrix
self.notify(old)
return self
Expand Down
2 changes: 1 addition & 1 deletion gaphas/painter/chain.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import Collection
from collections.abc import Collection

from cairo import Context as CairoContext

Expand Down
2 changes: 1 addition & 1 deletion gaphas/painter/freehand.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"""
from math import sqrt
from random import Random
from typing import Collection
from collections.abc import Collection

from cairo import Context as CairoContext

Expand Down
6 changes: 4 additions & 2 deletions gaphas/painter/itempainter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import Collection, Optional
from __future__ import annotations

from collections.abc import Collection

from cairo import LINE_JOIN_ROUND
from cairo import Context as CairoContext
Expand All @@ -8,7 +10,7 @@


class ItemPainter:
def __init__(self, selection: Optional[Selection] = None) -> None:
def __init__(self, selection: Selection | None = None) -> None:
self.selection = selection or Selection()

def paint_item(self, item: Item, cairo: CairoContext) -> None:
Expand Down
6 changes: 3 additions & 3 deletions gaphas/quadtree.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@
from __future__ import annotations

import operator
from typing import Callable, Generic, Iterable, Tuple, TypeVar
from typing import Callable, Generic, Iterable, TypeVar

from gaphas.geometry import rectangle_contains, rectangle_intersects
from gaphas.geometry import rectangle_contains, rectangle_intersects, Rect

Bounds = Tuple[float, float, float, float] # x, y, width, height
Bounds = Rect

T = TypeVar("T")
D = TypeVar("D")
Expand Down
5 changes: 3 additions & 2 deletions gaphas/segment.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Allow for easily adding segments to lines."""
from __future__ import annotations

from functools import singledispatch
from typing import Optional
from typing import Union

from gaphas.connector import Handle, LinePort
from gaphas.cursor import DEFAULT_CURSOR, LINE_CURSOR, cursor, line_hover
Expand Down Expand Up @@ -211,7 +212,7 @@ def paint(self, _items, cairo):


@cursor.register
def line_segment_hover(item: Line, handle: Optional[Handle], pos: Pos) -> str:
def line_segment_hover(item: Line, handle: Union[Handle, None], pos: Pos) -> str:
if not handle:
handles = item.handles()
if any(
Expand Down
Loading

0 comments on commit 7b27506

Please sign in to comment.