Fix RUF015 (next() instead of list comprehensions[0])

https://docs.astral.sh/ruff/rules/-iterable-allocation-for-first-element/
This commit is contained in:
Andrej730
2025-06-16 12:29:41 +05:00
parent b486b32c8d
commit a12bb343ca
29 changed files with 64 additions and 61 deletions
+7 -6
View File
@@ -39,13 +39,14 @@ exclude = [
[tool.ruff.lint]
select = [
# Default Ruff rules.
# "E4", # imports
# "E7", # statements
"E9", # io errors
# "F", # pyflakes
# "E4", # imports
# "E7", # statements
"E9", # io errors
# "F", # pyflakes
#
"FA", # future annotations
"UP", # pyupgrade
"FA", # future annotations
"UP", # pyupgrade
"RUF015", # next() > list_comprehension[0]
]
ignore = [
"FA100", # Conflicts with Blender using annotations for props definitions.
+4 -4
View File
@@ -177,7 +177,7 @@ class CadFillet(bpy.types.Operator):
selected_edges.append(cut_edges[1])
# Calculate the distance to slide each edge to make space for the fillet arc
shared_vert = list(set(selected_edges[0].verts) & set(selected_edges[1].verts))[0]
shared_vert = next(iter(set(selected_edges[0].verts) & set(selected_edges[1].verts)))
v1 = selected_edges[0].other_vert(shared_vert)
v2 = selected_edges[1].other_vert(shared_vert)
dir1 = (v1.co - shared_vert.co).normalized()
@@ -205,7 +205,7 @@ class CadFillet(bpy.types.Operator):
# If faces are involved, then the chamfer edge protects existing faces from the newly created fillet.
# If no faces are involved, we delete the chamfer edge.
if is_wire:
chamfer_edge = [e for e in bm.edges if shared_vert in e.verts and v2 in e.verts][0]
chamfer_edge = next(e for e in bm.edges if shared_vert in e.verts and v2 in e.verts)
bm.edges.remove(chamfer_edge)
bm.verts.index_update()
@@ -675,7 +675,7 @@ class AddIfcArcIndexFillet(bpy.types.Operator):
bm = bmesh.from_edit_mesh(self.mesh)
edges = [e for e in bm.edges if e.select and not e.hide]
mid = list(set(edges[0].verts) & set(edges[1].verts))[0]
mid = next(iter(set(edges[0].verts) & set(edges[1].verts)))
v1 = edges[0].other_vert(mid)
v2 = edges[1].other_vert(mid)
assert v1 and v2
@@ -738,7 +738,7 @@ class AddIfcArcIndexFillet(bpy.types.Operator):
bmesh.ops.remove_doubles(bm, verts=all_verts, dist=1e-4)
# Calculate the distance to slide each edge to make space for the fillet arc
shared_vert = list(set(selected_edges[0].verts) & set(selected_edges[1].verts))[0]
shared_vert = next(iter(set(selected_edges[0].verts) & set(selected_edges[1].verts)))
v1 = selected_edges[0].other_vert(shared_vert)
v2 = selected_edges[1].other_vert(shared_vert)
assert v1 and v2
@@ -1062,7 +1062,7 @@ class CreateDrawing(bpy.types.Operator):
# file 2 only has the groups we are interested in.
# in fact in the approach, it's only a single group
g2 = list(yield_groups(svg2))[0]
g2 = next(yield_groups(svg2))
# Loop over the cell paths
for pi, p in enumerate(g2.getElementsByTagName("path")):
@@ -1223,12 +1223,12 @@ class DuplicateMoveLinkedAggregate(bpy.types.Operator):
def custom_incremental_naming_for_element_assembly(old_to_new):
for new in old_to_new.values():
if new[0].is_a("IfcElementAssembly"):
group_elements = [
group_elements: list[ifcopenshell.entity_instance] = next(
r.RelatedObjects
for r in getattr(new[0], "HasAssignments", []) or []
if r.is_a("IfcRelAssignsToGroup")
if "BBIM_Linked_Aggregate" in r.RelatingGroup.Name
][0]
)
number = len(group_elements) - 1
number = f"{number:02d}"
@@ -1365,12 +1365,12 @@ class RefreshLinkedAggregate(bpy.types.Operator, tool.Ifc.Operator):
tool.Geometry.delete_ifc_object(tool.Ifc.get_object(element))
def get_original_names(element: ifcopenshell.entity_instance) -> dict[int, dict[int, str]]:
group = [
group = next(
r.RelatingGroup
for r in getattr(element, "HasAssignments", []) or []
if r.is_a("IfcRelAssignsToGroup")
if self.group_name in r.RelatingGroup.Name
][0].id()
).id()
original_names[group] = {}
pset = ifcopenshell.util.element.get_pset(element, self.pset_name)
@@ -1506,7 +1506,7 @@ class RefreshLinkedAggregate(bpy.types.Operator, tool.Ifc.Operator):
for group in linked_aggregate_groups:
elements = tool.Drawing.get_group_elements(tool.Ifc.get().by_id(group))
if len(linked_aggregate_groups) > 1:
base_instance = [e for e in elements if e in selected_parents][0]
base_instance = next(e for e in elements if e in selected_parents)
instances_to_refresh = elements
elif (len(linked_aggregate_groups) == 1) and (len(selected_parents) > 1):
@@ -102,7 +102,7 @@ class DumbProfileGenerator:
def create_profile(self):
ifc_classes = ifcopenshell.util.type.get_applicable_entities(self.relating_type.is_a(), self.file.schema)
# Standard cases are deprecated, so let's cull them
ifc_class = [c for c in ifc_classes if "StandardCase" not in c][0]
ifc_class = next(c for c in ifc_classes if "StandardCase" not in c)
mesh = bpy.data.meshes.new("Dummy")
obj = bpy.data.objects.new(tool.Model.generate_occurrence_name(self.relating_type, ifc_class), mesh)
@@ -296,9 +296,9 @@ class ExtendProfile(bpy.types.Operator, tool.Ifc.Operator):
if len(selected_objs) == 2:
if self.join_type == "L":
joiner.join_L([o for o in selected_objs if o != context.active_object][0], context.active_object)
joiner.join_L(next(o for o in selected_objs if o != context.active_object), context.active_object)
elif self.join_type == "V":
joiner.join_V([o for o in selected_objs if o != context.active_object][0], context.active_object)
joiner.join_V(next(o for o in selected_objs if o != context.active_object), context.active_object)
if len(selected_objs) < 2:
return {"FINISHED"}
if self.join_type == "T":
+2 -2
View File
@@ -248,9 +248,9 @@ def generate_hipped_roof_bmesh(
for angled_edge, edge_angle in angled_edges:
if angled_edge == verts:
face_angles[edge.link_faces[0]] = edge_angle
ridge_vert = [v for v in face_verts if v.co.copy().freeze() not in verts][0]
ridge_vert = next(v for v in face_verts if v.co.copy().freeze() not in verts)
if len(ridge_vert.link_edges) == 3:
ridge_edge = [e for e in ridge_vert.link_edges if e not in edge.link_faces[0].edges][0]
ridge_edge = next(e for e in ridge_vert.link_edges if e not in edge.link_faces[0].edges)
other_ridge_vert = ridge_edge.other_vert(ridge_vert)
else:
# We cannot actually get this correct without a weighted
+1 -1
View File
@@ -127,7 +127,7 @@ class DumbSlabGenerator:
def create_slab(self):
ifc_classes = ifcopenshell.util.type.get_applicable_entities(self.relating_type.is_a(), self.file.schema)
# Standard cases are deprecated, so let's cull them
ifc_class = [c for c in ifc_classes if "StandardCase" not in c][0]
ifc_class = next(c for c in ifc_classes if "StandardCase" not in c)
mesh = bpy.data.meshes.new("Dummy")
obj = bpy.data.objects.new(tool.Model.generate_occurrence_name(self.relating_type, ifc_class), mesh)
@@ -82,7 +82,7 @@ class CreateNewSverchokGraph(bpy.types.Operator, tool.Ifc.Operator):
sverchok.ui.sv_temporal_viewers.add_temporal_viewer_draw(
node_group.nodes, node_group.links, plane, cut_links=True
)
viewer = [n for n in node_group.nodes if n.bl_idname == "SvViewerDrawMk4"][0]
viewer = next(n for n in node_group.nodes if n.bl_idname == "SvViewerDrawMk4")
viewer.label = f"IFCOutput {viewer.label}"
props.node_group = node_group
+2 -2
View File
@@ -22,7 +22,7 @@ import ifcopenshell.api.pset
import ifcopenshell.util.date
def calculate_quantities(usecase_path, ifc_file, settings):
def calculate_quantities(usecase_path, ifc_file: ifcopenshell.file, settings):
if not set(["ScheduleStart", "ScheduleFinish", "ScheduleDuration"]).intersection(
set(settings["attributes"].keys())
):
@@ -30,7 +30,7 @@ def calculate_quantities(usecase_path, ifc_file, settings):
element = settings["task_time"]
if not element.ScheduleDuration:
return
task = [e for e in ifc_file.get_inverse(element) if e.is_a("IfcTask")][0]
task = next(e for e in ifc_file.get_inverse(element) if e.is_a("IfcTask"))
qto = ifcopenshell.api.pset.add_qto(
ifc_file, should_run_listeners=False, product=task, name="Qto_TaskBaseQuantities"
)
+2 -2
View File
@@ -1032,9 +1032,9 @@ class DumbWallGenerator:
tool.Blender.select_object(obj)
return obj
def get_relating_type_class(self, relating_type):
def get_relating_type_class(self, relating_type: ifcopenshell.entity_instance) -> str:
classes = ifcopenshell.util.type.get_applicable_entities(relating_type.is_a(), tool.Ifc.get().schema)
return [c for c in classes if "StandardCase" not in c][0]
return next(c for c in classes if "StandardCase" not in c)
class DumbWallPlaner:
@@ -140,7 +140,7 @@ class UpdateIfcPatchArguments(bpy.types.Operator):
if "file" in data_type or is_filepath_argument:
data_type = ["file"]
data_type = [dt for dt in data_type if dt != "NoneType"][0]
data_type = next(dt for dt in data_type if dt != "NoneType")
data_types: dict[str, AttributeDataType] = {
"Literal": "enum",
@@ -320,7 +320,7 @@ class ChangeLibraryElement(bpy.types.Operator):
for element in elements:
ifc_classes_elements[element.is_a()].append(element)
if len(ifc_classes_elements) == 1 and list(ifc_classes_elements)[0] == self.element_name:
if len(ifc_classes_elements) == 1 and next(iter(ifc_classes_elements)) == self.element_name:
for name, ifc_definition_id in sorted(
[(self.get_name(e), e.id()) for e in ifc_classes_elements[self.element_name]]
):
+2 -1
View File
@@ -250,7 +250,8 @@ class BIM_PT_resources(Panel):
if resource["BaseQuantity"]:
quantity = resource["BaseQuantity"]
value = quantity[[k for k in quantity.keys() if "Value" in k][0]]
key = next(k for k in quantity.keys() if "Value" in k)
value = quantity[key]
row = self.layout.row(align=True)
row.label(text=quantity["Name"])
row.label(text="{0:.2f}".format(value))
@@ -199,7 +199,7 @@ class EnableEditingStructuralBoundaryCondition(bpy.types.Operator):
elif isinstance(value, float):
new.float_value = 0.0 if new.is_null else value
new.data_type = "float"
new.enum_value = [i for i in enum_items if i != "IfcBoolean"][0]
new.enum_value = next(i for i in enum_items if i != "IfcBoolean")
elif data_type == "string":
new.string_value = "" if new.is_null else value
new.data_type = "string"
@@ -975,7 +975,7 @@ class EnableEditingBoundaryCondition(bpy.types.Operator):
elif isinstance(value, float):
new.float_value = 0.0 if new.is_null else value
new.data_type = "float"
new.enum_value = [i for i in enum_items if i != "IfcBoolean"][0]
new.enum_value = next(i for i in enum_items if i != "IfcBoolean")
elif data_type == "string":
new.string_value = "" if new.is_null else value
new.data_type = "string"
+3 -3
View File
@@ -177,9 +177,9 @@ class TestRemoveRelation(NewFile):
def test_run(self):
TestAddRelation().test_run()
assert BrickStore.graph
source, relation, destination = list(
BrickStore.graph.triples((None, URIRef("https://brickschema.org/schema/Brick#feeds"), None))
)[0]
source, relation, destination = next(
iter(BrickStore.graph.triples((None, URIRef("https://brickschema.org/schema/Brick#feeds"), None)))
)
subject.remove_relation(source, relation, destination)
assert not list(
BrickStore.graph.triples(
+2 -2
View File
@@ -55,7 +55,7 @@ class TestAddClassificationReferenceFromBSDD(NewFile):
bpy.ops.bim.add_classification_reference_from_bsdd(obj="IfcSpace/Cube", obj_type="Object")
refs = ifcopenshell.util.classification.get_references(element)
assert len(refs) == 1
assert list(refs)[0].Location.startswith(uri)
assert next(iter(refs)).Location.startswith(uri)
def test_add_classification_refence_with_props(self):
bpy.ops.bim.create_project()
@@ -92,7 +92,7 @@ class TestAddClassificationReferenceFromBSDD(NewFile):
assert pset and pset["Handicap Accessible"] == True
refs = ifcopenshell.util.classification.get_references(element)
assert len(refs) == 1
assert list(refs)[0].Location.startswith(uri)
assert next(iter(refs)).Location.startswith(uri)
def test_add_clasification_reference_with_object_type(self):
bpy.ops.bim.create_project()
+1 -1
View File
@@ -106,7 +106,7 @@ class TestGetManualBooleans(NewFile):
assert set(subject.get_booleans(element, representation)) == set(bools)
assert len(subject.get_manual_booleans(element, representation)) == 0
bool1 = list(bools)[0]
bool1 = bools[0]
subject.mark_manual_booleans(element, [bool1])
assert set(subject.get_manual_booleans(element, representation)) == {bool1}
+3 -3
View File
@@ -2,8 +2,8 @@ from bsdd import Client
client = Client()
ifc4x3_uri = [l["uri"] for l in client.get_dictionary()["dictionaries"] if "4.3" in l["uri"]][0]
nbs_uri = [l["uri"] for l in client.get_dictionary()["dictionaries"] if "Uniclass 2015" == l["name"]][0]
ifc4x3_uri = next(l["uri"] for l in client.get_dictionary()["dictionaries"] if "4.3" in l["uri"])
nbs_uri = next(l["uri"] for l in client.get_dictionary()["dictionaries"] if "Uniclass 2015" == l["name"])
def get_ifc_classes():
@@ -30,7 +30,7 @@ def test_get_nbs_classes():
def test_get_class():
uri_light_fixture = [l for l in get_ifc_classes()["classes"] if "IfcLightFixture" == l["code"]][0]["uri"]
uri_light_fixture = next(l for l in get_ifc_classes()["classes"] if "IfcLightFixture" == l["code"])["uri"]
ifc4x3_light_fixture = client.get_class(uri_light_fixture)
assert "Maintenance Factor" and "Light Fixture Mounting Type" in [
l["name"] for l in ifc4x3_light_fixture["classProperties"]
@@ -55,7 +55,7 @@ class COMMANDFILE:
conn["relatedElements"] = []
for el in elements:
for rel in el["connections"]:
conn = [c for c in connections if c["referenceName"] == rel["relatedConnection"]][0]
conn = next(c for c in connections if c["referenceName"] == rel["relatedConnection"])
conn["relatedElements"].append(rel)
# End <--
+1 -1
View File
@@ -192,7 +192,7 @@ class MODEL:
el["linkObjs"] = [None for _ in el["connections"]]
for j, rel in enumerate(el["connections"]):
conn = [c for c in connections if c["referenceName"] == rel["relatedConnection"]][0]
conn = next(c for c in connections if c["referenceName"] == rel["relatedConnection"])
if rel["eccentricity"]:
rel["index"] = len(conn["relatedElements"]) + 1
+1 -1
View File
@@ -164,7 +164,7 @@ class CommandFileConstructor:
self.calculateRestraints(conn)
for el in elements:
for rel in el["connections"]:
conn = [c for c in connections if c["ref_id"] == rel["related_connection"]][0]
conn = next(c for c in connections if c["ref_id"] == rel["related_connection"])
rel["conn_string"] = None
if conn["geometry_type"] == "Vertex":
rel["conn_string"] = "_0DC_"
+1 -1
View File
@@ -286,7 +286,7 @@ class IfcCsv:
reverse = sort_data["order"] == "DESC"
self.results = sorted(self.results, key=lambda x: natural_sort(x[i]), reverse=reverse)
else:
if include_global_id and len(list(self.results)[0]) > 1:
if include_global_id and len(next(iter(self.results))) > 1:
self.results = sorted(self.results, key=lambda x: x[1])
elif not include_global_id:
self.results = sorted(self.results, key=lambda x: x[0])
+2 -1
View File
@@ -180,7 +180,8 @@ class Writer:
continue
if not headers:
headers = list(data[list(data.keys())[0]].keys())
key = next(iter(data.keys()))
headers = list(data[key].keys())
rows = []
for row in data.values():
@@ -48,14 +48,14 @@ def create_segment_representations(
representation.RepresentationIdentifier == "FootPrint" and representation.RepresentationType == "Curve2D"
):
curve = ifcopenshell.api.alignment.get_basis_curve(alignment)
nested_alignment = [
nested_alignment = next(
c for c in ifcopenshell.util.element.get_components(alignment) if c.is_a("IfcAlignmentHorizontal")
][0]
)
elif representation.RepresentationIdentifier == "Axis" and representation.RepresentationType == "Curve3D":
curve = ifcopenshell.api.alignment.get_curve(alignment)
nested_alignment = [
nested_alignment = next(
c for c in ifcopenshell.util.element.get_components(alignment) if c.is_a("IfcAlignmentVertical")
][0]
)
curve_segments = curve.Segments
segments = nested_alignment.IsNestedBy[0].RelatingObjects
+1 -1
View File
@@ -296,7 +296,7 @@ def main(
# file 2 only has the groups we are interested in.
# in fact in the approach, it's only a single group
g2 = list(yield_groups(svg2))[0]
g2 = next(yield_groups(svg2))
# These are attributes on the original group that we can use to reconstruct
# a 4x4 matrix of the projection used in the SVG generation process
@@ -37,7 +37,7 @@ class TestAddBoolean(test.bootstrap.IFC4):
booleans = ifcopenshell.api.geometry.add_boolean(self.file, first, [second])
assert len(booleans) == 1
boolean = list(booleans)[0]
boolean = booleans[0]
assert boolean.is_a("IfcBooleanResult")
assert boolean.FirstOperand == first
assert boolean.SecondOperand == second
@@ -107,16 +107,16 @@ class TestAddBoolean(test.bootstrap.IFC4):
assert len(rep.Items) == 2
assert self.file.get_total_inverses(first1) == 1
result = list(self.file.get_inverse(first1))[0]
result = next(iter(self.file.get_inverse(first1)))
assert result.FirstOperand == first1
assert result.SecondOperand == second1
result2 = list(self.file.get_inverse(result))[0]
result2 = next(iter(self.file.get_inverse(result)))
assert result2.FirstOperand == result
# Second2 is now used twice. Reusing is OK (albeit confusing), so long as things don't get recursive.
assert result2.SecondOperand == second2
assert self.file.get_total_inverses(first2) == 1
result3 = list(self.file.get_inverse(first2))[0]
result3 = next(iter(self.file.get_inverse(first2)))
assert result3.FirstOperand == first2
assert result3.SecondOperand == second2
@@ -81,8 +81,8 @@ class TestGetReferences(test.bootstrap.IFC4):
reference=reference2,
classification=classification,
)
reference1 = [r for r in self.file.by_type("IfcClassificationReference") if r.Identification == "1"][0]
reference2 = [r for r in self.file.by_type("IfcClassificationReference") if r.Identification == "2"][0]
reference1 = next(r for r in self.file.by_type("IfcClassificationReference") if r.Identification == "1")
reference2 = next(r for r in self.file.by_type("IfcClassificationReference") if r.Identification == "2")
assert subject.get_references(element_type) == set([reference2])
assert subject.get_references(element) == set([reference1])
@@ -166,9 +166,9 @@ class Patcher:
related_elements.append(door_copy)
door.ContainedInStructure[0].RelatedElements = related_elements
body_context = [
body_context = next(
c for c in self.file.by_type("IfcGeometricRepresentationSubContext") if c.ContextIdentifier == "Body"
][0]
)
for subelement in self.file.traverse(footprint_reps[0]):
if not subelement.is_a("IfcShapeRepresentation"):
continue
+2 -2
View File
@@ -676,11 +676,11 @@ class Property(Facet):
props[pset_name] = {}
if isinstance(self.baseName, str):
prop = pset_props.get(self.baseName)
if prop == "UNKNOWN" and [
if prop == "UNKNOWN" and next(
p
for p in self.get_properties(inst.wrapped_data.file.by_id(pset_props["id"]))
if p.Name == self.baseName
][0].NominalValue.is_a("IfcLogical"):
).NominalValue.is_a("IfcLogical"):
pass
elif prop is not None and prop != "":
props[pset_name][self.baseName] = prop