Skip to content
This repository was archived by the owner on Apr 11, 2025. It is now read-only.

Commit d892477

Browse files
committed
[REF]: core set_border: Improve performance, Fix index out of Range
1. **Variable Initialization**: We store `len(self.rows)` and `len(self.cols)` in `num_rows` and `num_cols` respectively to avoid recalculating these values on each iteration. 2. **Error Handling**: Before trying to set borders, we check if the number of rows and columns is valid. If either is zero, the method returns early. Additionally, we check if `self.cells` has the expected structure. If not, we raise a `ValueError`. 3. **Looping through Indices**: Instead of using `enumerate()`, use a simple `range()` loop since we only need the index and not the item itself. This can enhance readability and possibly performance.
1 parent 88a3c3d commit d892477

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

camelot/core.py

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -726,12 +726,31 @@ def _update_horizontal_edges(self, start, end, index):
726726

727727
def set_border(self):
728728
"""Sets table border edges to True."""
729-
for index, _row in enumerate(self.rows):
730-
self.cells[index][0].left = True
731-
self.cells[index][len(self.cols) - 1].right = True
732-
for index, _col in enumerate(self.cols):
733-
self.cells[0][index].top = True
734-
self.cells[len(self.rows) - 1][index].bottom = True
729+
num_rows = len(self.rows)
730+
num_cols = len(self.cols)
731+
732+
# Ensure cells structure is valid
733+
if num_rows == 0 or num_cols == 0:
734+
return self # No rows or columns, nothing to do
735+
736+
# Check if cells have the expected structure
737+
if len(self.cells) != num_rows or any(
738+
len(row) != num_cols for row in self.cells
739+
):
740+
raise ValueError(
741+
"Inconsistent cells structure: cells should match the dimensions of rows and cols."
742+
)
743+
744+
# Set left and right borders for each row
745+
for row_index in range(num_rows):
746+
self.cells[row_index][0].left = True # Set the left border
747+
self.cells[row_index][num_cols - 1].right = True # Set the right border
748+
749+
# Set top and bottom borders for each column
750+
for col_index in range(num_cols):
751+
self.cells[0][col_index].top = True # Set the top border
752+
self.cells[num_rows - 1][col_index].bottom = True # Set the bottom border
753+
735754
return self
736755

737756
def copy_spanning_text(self, copy_text=None):

0 commit comments

Comments
 (0)