Minor mypy improvements

This commit is contained in:
gumyr 2023-10-05 09:29:18 -04:00
parent 92b09be2db
commit cbb827d271
2 changed files with 52 additions and 30 deletions

View file

@ -48,7 +48,7 @@ import warnings
from abc import ABC, abstractmethod
from itertools import product
from math import sqrt
from typing import Callable, Iterable, Union
from typing import Callable, Iterable, Optional, Union
from typing_extensions import Self
from build123d.build_enums import Align, Mode, Select
@ -162,9 +162,10 @@ class Builder(ABC):
return self._obj.bounding_box().diagonal if self._obj else 0.0
@property
def new_edges(self) -> ShapeList(Edge):
def new_edges(self) -> ShapeList[Edge]:
"""Edges that changed during last operation"""
return new_edges(*([self.obj_before] + self.to_combine), combined=self._obj)
before_list = [] if self.obj_before is None else [self.obj_before]
return new_edges(*(before_list + self.to_combine), combined=self._obj)
def __init__(
self,
@ -174,13 +175,16 @@ class Builder(ABC):
self.mode = mode
self.workplanes = WorkplaneList._convert_to_planes(workplanes)
self._reset_tok = None
self._python_frame = inspect.currentframe().f_back.f_back
current_frame = inspect.currentframe()
assert current_frame is not None
assert current_frame.f_back is not None
self._python_frame = current_frame.f_back.f_back
self.builder_parent = None
self.lasts: dict = {Vertex: [], Edge: [], Face: [], Solid: []}
self.workplanes_context = None
self.exit_workplanes = None
self.obj_before: Shape = None
self.to_combine: list[Shape] = None
self.obj_before: Optional[Shape] = None
self.to_combine: list[Shape] = []
def __enter__(self):
"""Upon entering record the parent and a token to restore contextvars"""
@ -333,7 +337,7 @@ class Builder(ABC):
except:
plane = Plane(origin=(0, 0, 0), z_dir=face.normal_at())
face: Face = plane.to_local_coords(face)
face = plane.to_local_coords(face)
face.move(Location((0, 0, -face.center().Z)))
if face.normal_at().Z > 0: # Flip the face if up-side-down
aligned.append(face)
@ -1183,5 +1187,5 @@ def _vector_add_sub_wrapper(original_op: Callable[[Vector, VectorLike], Vector])
logger.debug("monkey-patching `Vector.add` and `Vector.sub`")
Vector.add = _vector_add_sub_wrapper(Vector.add)
Vector.sub = _vector_add_sub_wrapper(Vector.sub)
Vector.add = _vector_add_sub_wrapper(Vector.add) # type: ignore
Vector.sub = _vector_add_sub_wrapper(Vector.sub) # type: ignore

View file

@ -23,15 +23,11 @@ license:
"""
# pylint: disable=no-name-in-module
from typing import Dict, Any, List
from json import dumps
from typing import Any, Dict, List
from IPython.display import Javascript
from vtkmodules.vtkIOXML import vtkXMLPolyDataWriter
# from build123d.topology import Shape
DEFAULT_COLOR = [1, 0.8, 0, 1]
TEMPLATE_RENDER = """
@ -181,11 +177,24 @@ new Promise(
def to_vtkpoly_string(
# shape: Shape, tolerance: float = 1e-3, angular_tolerance: float = 0.1
shape: "Shape",
tolerance: float = 1e-3,
angular_tolerance: float = 0.1,
shape: Any, tolerance: float = 1e-3, angular_tolerance: float = 0.1
) -> str:
"""to_vtkpoly_string
Args:
shape (Shape): object to convert
tolerance (float, optional): Defaults to 1e-3.
angular_tolerance (float, optional): Defaults to 0.1.
Raises:
ValueError: not a valid Shape
Returns:
str: vtkpoly str
"""
if not hasattr(shape, "wrapped"):
raise ValueError(f"Type {type(shape)} is not supported")
writer = vtkXMLPolyDataWriter()
writer.SetWriteToOutputString(True)
writer.SetInputData(shape.to_vtk_poly_data(tolerance, angular_tolerance, True))
@ -194,22 +203,31 @@ def to_vtkpoly_string(
return writer.GetOutputString()
def display(shape):
def display(shape: Any) -> Javascript:
"""display
Args:
shape (Shape): object to display
Raises:
ValueError: not a valid Shape
Returns:
Javascript: code
"""
payload: List[Dict[str, Any]] = []
# if isinstance(shape, Shape):
if hasattr(shape, "wrapped"): # Is a "Shape"
payload.append(
dict(
shape=to_vtkpoly_string(shape),
color=DEFAULT_COLOR,
position=[0, 0, 0],
orientation=[0, 0, 0],
)
)
else:
if not hasattr(shape, "wrapped"): # Is a "Shape"
raise ValueError(f"Type {type(shape)} is not supported")
payload.append(
dict(
shape=to_vtkpoly_string(shape),
color=DEFAULT_COLOR,
position=[0, 0, 0],
orientation=[0, 0, 0],
)
)
code = TEMPLATE.format(data=dumps(payload), element="element", ratio=0.5)
return Javascript(code)