Minor pylint related changes

This commit is contained in:
Roger Maitland 2023-02-13 13:29:33 -05:00
parent b965f190a8
commit f9af5af09b
7 changed files with 111 additions and 85 deletions

View file

@ -2,3 +2,10 @@
# Good variable names which should always be accepted, separated by a comma
good-names=i,j,k,x,y,z,ex,Run,_,X,Y,Z,XY,YZ,ZX,XZ,YX,ZY
disable=
unsubscriptable-object, # False positives
use-a-generator, # all([..]) is just fine
protected-access, # _variable to be hiddened from external users
too-many-arguments, # CAD is complex
too-few-public-methods # Objects and Operations will not have methods outside of _init

View file

@ -29,21 +29,14 @@ from __future__ import annotations
import inspect
import contextvars
from itertools import product
from abc import ABC, abstractmethod, abstractstaticmethod
from math import sqrt, pi
from abc import ABC, abstractmethod
from math import sqrt
from typing import Iterable, Union
import logging
from build123d.build_enums import (
Align,
Select,
Kind,
Keep,
Mode,
Transition,
FontStyle,
Until,
SortBy,
GeomType,
)
from build123d.direct_api import (
@ -59,7 +52,6 @@ from build123d.direct_api import (
Shape,
Vertex,
Plane,
Shell,
ShapeList,
)
@ -114,6 +106,8 @@ class Builder(ABC):
self.builder_parent = None
self.last_vertices: list[Vertex] = []
self.last_edges: list[Edge] = []
self.last_faces: list[Face] = []
self.last_solids: list[Solid] = []
self.workplanes_context = None
self.active: bool = False # is the builder context active
self.exit_workplanes = None
@ -207,8 +201,7 @@ class Builder(ABC):
raise RuntimeError(
f"No valid context found, use one of {caller._applies_to}"
)
else:
raise RuntimeError(f"No valid context found-common")
raise RuntimeError("No valid context found-common")
return result
@ -392,12 +385,11 @@ class LocationList:
def __next__(self):
"""While not through all the locations, return the next one"""
if self.location_index < len(self.locations):
if self.location_index >= len(self.locations):
raise StopIteration
result = self.locations[self.location_index]
self.location_index += 1
return result
else:
raise StopIteration
@classmethod
def _get_context(cls):
@ -616,7 +608,7 @@ class GridLocations(LocationList):
align_offset = []
for i in range(2):
if align[i] == Align.MIN:
align_offset.append(0.)
align_offset.append(0.0)
elif align[i] == Align.CENTER:
align_offset.append(-size[i] / 2)
elif align[i] == Align.MAX:
@ -688,12 +680,11 @@ class WorkplaneList:
def __next__(self):
"""While not through all the workplanes, return the next one"""
if self.plane_index < len(self.workplanes):
if self.plane_index >= len(self.workplanes):
raise StopIteration
result = self.workplanes[self.plane_index]
self.plane_index += 1
return result
else:
raise StopIteration
@classmethod
def _get_context(cls):

View file

@ -36,8 +36,6 @@ from build123d.direct_api import (
Vector,
Compound,
Location,
VectorLike,
ShapeList,
Face,
Plane,
Matrix,
@ -101,7 +99,7 @@ class Add(Compound):
elif isinstance(rotation, tuple):
rotation = Rotation(*rotation)
objects = tuple([obj.moved(rotation) for obj in objects])
objects = [obj.moved(rotation) for obj in objects]
new_edges = [obj for obj in objects if isinstance(obj, Edge)]
new_wires = [obj for obj in objects if isinstance(obj, Wire)]
new_faces = [obj for obj in objects if isinstance(obj, Face)]

View file

@ -27,7 +27,7 @@ license:
"""
import copy
import inspect
from math import sin, cos, radians, degrees, atan2, sqrt, copysign
from math import sin, cos, radians, sqrt, copysign
from typing import Union, Iterable
from build123d.build_enums import Select, Mode, AngularDirection
from build123d.direct_api import (
@ -37,7 +37,6 @@ from build123d.direct_api import (
Vector,
Compound,
Location,
Matrix,
VectorLike,
ShapeList,
Face,
@ -93,11 +92,11 @@ class BuildLine(Builder):
self.line: Compound = None
super().__init__(workplane, mode=mode)
def faces(self):
def faces(self, *args):
"""faces() not implemented"""
raise NotImplementedError("faces() doesn't apply to BuildLine")
def solids(self):
def solids(self, *args):
"""solids() not implemented"""
raise NotImplementedError("solids() doesn't apply to BuildLine")
@ -172,8 +171,7 @@ class BuildLine(Builder):
raise RuntimeError(
f"No valid context found, use one of {caller._applies_to}"
)
else:
raise RuntimeError(f"No valid context found")
raise RuntimeError("No valid context found")
return result
@ -298,9 +296,10 @@ class EllipticalStartArc(Edge):
end (VectorLike): final point of arc
x_radius (float): semi-major radius
y_radius (float): semi-minor radius
rotation (float, optional): the angle from the x-axis of the plane to the x-axis of the ellipse.
Defaults to 0.0.
large_arc (bool, optional): True if the arc spans greater than 180 degrees. Defaults to True.
rotation (float, optional): the angle from the x-axis of the plane to the x-axis
of the ellipse. Defaults to 0.0.
large_arc (bool, optional): True if the arc spans greater than 180 degrees.
Defaults to True.
sweep_flag (bool, optional): False if the line joining center to arc sweeps through
decreasing angles, or True if it sweeps through increasing angles. Defaults to True.
plane (Plane, optional): base plane. Defaults to Plane.XY.
@ -321,7 +320,6 @@ class EllipticalStartArc(Edge):
plane: Plane = Plane.XY,
mode: Mode = Mode.ADD,
) -> Edge:
# Debugging incomplete
raise RuntimeError("Implementation incomplete")

View file

@ -29,10 +29,9 @@ license:
"""
import inspect
from warnings import warn
from math import radians, tan, sqrt
from math import radians, tan
from typing import Union, Iterable
from build123d.build_enums import Mode, Until, Select, Transition, Align
from build123d.build_enums import Mode, Until, Transition, Align
from build123d.direct_api import (
Edge,
Wire,
@ -41,8 +40,6 @@ from build123d.direct_api import (
Compound,
Location,
VectorLike,
ShapeList,
Location,
Face,
Plane,
Axis,
@ -240,8 +237,7 @@ class BuildPart(Builder):
raise RuntimeError(
f"No valid context found, use one of {caller._applies_to}"
)
else:
raise RuntimeError(f"No valid context found")
raise RuntimeError("No valid context found")
return result
@ -534,7 +530,6 @@ class Loft(Solid):
_applies_to = [BuildPart._tag()]
def __init__(self, *sections: Face, ruled: bool = False, mode: Mode = Mode.ADD):
context: BuildPart = BuildPart._get_context(self)
context.validate_inputs(self, sections)
@ -555,7 +550,7 @@ class Loft(Solid):
new_solid = Solid.make_solid(
Shell.make_shell(new_solid.faces() + list(sections))
).clean()
if not new_solid.isValid():
if not new_solid.is_valid():
raise RuntimeError("Failed to create valid loft")
context._add_to_context(new_solid, mode=mode)
@ -1002,9 +997,9 @@ class Wedge(BasePartObject):
Create a wedge(s) and combine with part.
Args:
dx (float): distance along the X axis
dy (float): distance along the Y axis
dz (float): distance along the Z axis
xsize (float): distance along the X axis
ysize (float): distance along the Y axis
zsize (float): distance along the Z axis
xmin (float): minimum X location
zmin (float): minimum Z location
xmax (float): maximum X location
@ -1019,9 +1014,9 @@ class Wedge(BasePartObject):
def __init__(
self,
dx: float,
dy: float,
dz: float,
xsize: float,
ysize: float,
zsize: float,
xmin: float,
zmin: float,
xmax: float,
@ -1033,14 +1028,14 @@ class Wedge(BasePartObject):
context: BuildPart = BuildPart._get_context(self)
context.validate_inputs(self)
self.dx = dx
self.dy = dy
self.dz = dz
self.xsize = xsize
self.ysize = ysize
self.zsize = zsize
self.xmin = xmin
self.zmin = zmin
self.xmax = xmax
self.zmax = zmax
self.align = align
solid = Solid.make_wedge(dx, dy, dz, xmin, zmin, xmax, zmax)
solid = Solid.make_wedge(xsize, ysize, zsize, xmin, zmin, xmax, zmax)
super().__init__(solid=solid, rotation=rotation, align=align, mode=mode)

View file

@ -8,10 +8,6 @@ date: July 12th 2022
desc:
This python module is a library used to build planar sketches.
TODO:
- add center to arrays
- bug: offset_2d doesn't work on a Wire made from a single Edge
Instead of existing constraints how about constraints that return locations
on objects:
- two circles: c1, c2
@ -42,7 +38,7 @@ import inspect
from math import pi, sin, cos, tan, radians
from typing import Union
from build123d.hull import find_hull
from build123d.build_enums import Align, CenterOf, FontStyle, Mode
from build123d.build_enums import Align, FontStyle, Mode
from build123d.direct_api import (
Edge,
Wire,
@ -113,7 +109,7 @@ class BuildSketch(Builder):
self.last_faces = []
super().__init__(*workplanes, mode=mode)
def solids(self):
def solids(self, *args):
"""solids() not implemented"""
raise NotImplementedError("solids() doesn't apply to BuildSketch")
@ -225,8 +221,7 @@ class BuildSketch(Builder):
raise RuntimeError(
f"No valid context found, use one of {caller._applies_to}"
)
else:
raise RuntimeError(f"No valid context found")
raise RuntimeError("No valid context found")
return result
@ -326,7 +321,9 @@ class BaseSketchObject(Compound):
if align[i] == Align.MIN:
align_offset.append(-bbox.min.to_tuple()[i])
elif align[i] == Align.CENTER:
align_offset.append(-(bbox.min.to_tuple()[i] + bbox.max.to_tuple()[i]) / 2)
align_offset.append(
-(bbox.min.to_tuple()[i] + bbox.max.to_tuple()[i]) / 2
)
elif align[i] == Align.MAX:
align_offset.append(-bbox.max.to_tuple()[i])
else:
@ -756,7 +753,6 @@ class Text(BaseSketchObject):
rotation: float = 0,
mode: Mode = Mode.ADD,
) -> Compound:
context: BuildSketch = BuildSketch._get_context(self)
context.validate_inputs(self)

View file

@ -1064,21 +1064,22 @@ class Color:
def __init__(self, name: str):
"""Color from name
`OCCT Color Names <https://dev.opencascade.org/doc/refman/html/_quantity___name_of_color_8hxx.html>`_
`OCCT Color Names
<https://dev.opencascade.org/doc/refman/html/_quantity___name_of_color_8hxx.html>`_
Args:
name (str): color, e.g. "blue"
"""
@overload
def __init__(self, r: float, g: float, b: float, a: float = 0.0):
def __init__(self, red: float, green: float, blue: float, alpha: float = 0.0):
"""Color from RGBA and Alpha values
Args:
r (float): 0.0 <= red <= 1.0
g (float): 0.0 <= green <= 1.0
b (float): 0.0 <= blue <= 1.0
a (float, optional): 0.0 <= alpha <= 1.0. Defaults to 0.0.
red (float): 0.0 <= red <= 1.0
green (float): 0.0 <= green <= 1.0
blue (float): 0.0 <= blue <= 1.0
alpha (float, optional): 0.0 <= alpha <= 1.0. Defaults to 0.0.
"""
def __init__(self, *args, **kwargs):
@ -1088,13 +1089,13 @@ class Color:
if not exists:
raise ValueError(f"Unknown color name: {args[0]}")
elif len(args) == 3:
r, g, b = args
self.wrapped = Quantity_ColorRGBA(r, g, b, 1)
red, green, blue = args
self.wrapped = Quantity_ColorRGBA(red, green, blue, 1)
if kwargs.get("a"):
self.wrapped.SetAlpha(kwargs.get("a"))
elif len(args) == 4:
r, g, b, a = args
self.wrapped = Quantity_ColorRGBA(r, g, b, a)
red, green, blue, alpha = args
self.wrapped = Quantity_ColorRGBA(red, green, blue, alpha)
else:
raise ValueError(f"Unsupported arguments: {args}, {kwargs}")
@ -1102,10 +1103,10 @@ class Color:
"""
Convert Color to RGB tuple.
"""
a = self.wrapped.Alpha()
alpha = self.wrapped.Alpha()
rgb = self.wrapped.GetRGB()
return (rgb.Red(), rgb.Green(), rgb.Blue(), a)
return (rgb.Red(), rgb.Green(), rgb.Blue(), alpha)
class Location:
@ -3582,7 +3583,8 @@ class Shape(NodeMixin):
"""
path_length = path.length
shape_center = self.center()
# The derived classes of Shape implement center
shape_center = self.center() # pylint: disable=no-member
# Create text faces
text_faces = Compound.make_2d_text(
@ -4441,14 +4443,20 @@ class Compound(Shape, Mixin3D):
tree_label_width = max(level_sizes_per_level) + 1
result = ""
for pre, fill, node in RenderTree(self):
for pre, _fill, node in RenderTree(self):
treestr = "%s%s" % (pre, node.label)
result += f"{treestr.ljust(tree_label_width)}{node.__class__.__name__.ljust(8)} at {id(self):#x}, Location{repr(self.location)}\n"
result += (
f"{treestr.ljust(tree_label_width)}{node.__class__.__name__.ljust(8)} "
f"at {id(self):#x}, Location{repr(self.location)}\n"
)
return result
def __repr__(self):
if hasattr(self, "label") and hasattr(self, "children"):
result = f"Compound at {id(self):#x}, label({self.label}), #children({len(self.children)})"
result = (
f"Compound at {id(self):#x}, label({self.label}), "
f"#children({len(self.children)})"
)
else:
result = f"Compound at {id(self):#x}"
return result
@ -4474,6 +4482,35 @@ class Compound(Shape, Mixin3D):
return comp
def center(self, center_of: CenterOf = CenterOf.MASS) -> Vector:
"""Return center of object
Find center of object
Args:
center_of (CenterOf, optional): center option. Defaults to CenterOf.MASS.
Raises:
ValueError: Center of GEOMETRY is not supported for this object
NotImplementedError: Unable to calculate center of mass of this object
Returns:
Vector: center
"""
if center_of == CenterOf.GEOMETRY:
raise ValueError("Center of GEOMETRY is not supported for this object")
if center_of == CenterOf.MASS:
properties = GProp_GProps()
calc_function = shape_properties_LUT[shapetype(self.wrapped)]
if calc_function:
calc_function(self.wrapped, properties)
middle = Vector(properties.CentreOfMass())
else:
raise NotImplementedError
elif center_of == CenterOf.BOUNDING_BOX:
middle = self.center(CenterOf.BOUNDING_BOX)
return middle
@classmethod
def make_compound(cls, shapes: Iterable[Shape]) -> Compound:
"""Create a compound out of a list of shapes
@ -4852,7 +4889,8 @@ class Compound(Shape, Mixin3D):
return tcast(Compound, self._bool_op(self, to_intersect, intersect_op))
def get_type(
self, obj_type: Union[Type[Edge], Type[Face], Type[Shell], Type[Solid], Type[Wire]]
self,
obj_type: Union[Type[Edge], Type[Face], Type[Shell], Type[Solid], Type[Wire]],
) -> list[Union[Edge, Face, Shell, Solid, Wire]]:
"""get_type
@ -8142,7 +8180,8 @@ class BallJoint(Joint):
label (str): joint label
to_part (Union[Solid, Compound]): object to attach joint to
joint_location (Location): global location of joint
angular_range (tuple[ tuple[float, float], tuple[float, float], tuple[float, float] ], optional):
angular_range
(tuple[ tuple[float, float], tuple[float, float], tuple[float, float] ], optional):
X, Y, Z angle (min, max) pairs. Defaults to ((0, 360), (0, 360), (0, 360)).
angle_reference (Plane, optional): plane relative to part defining zero degrees of
rotation. Defaults to Plane.XY.
@ -8191,7 +8230,9 @@ class BallJoint(Joint):
label (str): _description_
to_part (Union[Solid, Compound]): _description_
joint_location (Location, optional): _description_. Defaults to Location().
angular_range (tuple[ tuple[float, float], tuple[float, float], tuple[float, float] ], optional): _description_. Defaults to ((0, 360), (0, 360), (0, 360)).
angular_range
(tuple[ tuple[float, float], tuple[float, float], tuple[float, float] ], optional):
_description_. Defaults to ((0, 360), (0, 360), (0, 360)).
angle_reference (Plane, optional): _description_. Defaults to Plane.XY.
"""
self.relative_location = to_part.location.inverse() * joint_location