Analyze the code for redundancies that violate the don't repeat yourself principle for…
- User
Analyze the code for redundancies that violate the don't repeat yourself principle for python code. Python 3.12 code: import math import re from typing import Any, Union, Callable from math import radians, pi, e, sqrt, log10, log, ceil
from PySide6.QtWidgets import ( QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLineEdit, QTextEdit, QScrollBar, QPushButton, QLabel, QFrame, QGridLayout ) from PySide6.QtGui import QFont from PySide6.QtCore import Qt, QSize
def convert_angle(func: Callable[[float], float], x: float, use_degrees: bool) -> float: """Apply trig function with optional degree conversion.""" return func(radians(x) if use_degrees else x)
def kilograms_to_pounds(kg: float) -> float: """Convert kilograms to pounds.""" return kg / 0.45359237
def pounds_to_kilograms(lb: float) -> float: """Convert pounds to kilograms.""" return lb * 0.45359237
def celsius_to_kelvin(c: float) -> float: """Convert Celsius to Kelvin.""" return c + 273.15
def kelvin_to_celsius(k: float) -> float: """Convert Kelvin to Celsius.""" return k - 273.15
def celsius_to_fahrenheit(c: float) -> float: """Convert Celsius to Fahrenheit.""" return c * 9 / 5 + 32
def fahrenheit_to_celsius(f: float) -> float: """Convert Fahrenheit to Celsius.""" return (f - 32) * 5 / 9
def capitalize_sentence(sentence: str) -> str: """Capitalize first letter of each word.""" return ' '.join(word.capitalize() for word in sentence.split())
def remove_duplicates(text: str) -> str: """Remove duplicate words and empty lines.""" words = ' '.join(line.strip() for line in text.splitlines() if line.strip()).split() return ' '.join(dict.fromkeys(words))
def get_safe_globals(use_degrees: bool, variables: dict) -> dict: """Provide safe globals for expression evaluation.""" trig_funcs = {'sin', 'cos', 'tan', 'asin', 'acos', 'atan'} safe_globals = { "sqrt": sqrt, "log": log10, "ln": log, "pi": pi, "e": e, "lb": kilograms_to_pounds, "kg": pounds_to_kilograms, "C": kelvin_to_celsius, "K": celsius_to_kelvin, "F": celsius_to_fahrenheit, "CF": fahrenheit_to_celsius, "capitalize": capitalize_sentence, "duplicates": remove_duplicates, } for func in trig_funcs: safe_globals[func] = lambda x, f=func: convert_angle(getattr(math, f), x, use_degrees) safe_globals.update(variables) return safe_globals
def preprocess_text_functions(expression: str) -> str: """Preprocess text functions with argument quotes.""" def add_quotes(match): func, args = match.groups() return f'{func}("{args}")' if func in ['capitalize', 'duplicates'] else match.group(0) return re.sub(r'\b(capitalize|duplicates)\s*(\s*([^)]+)\s*)', add_quotes, expression)
def validate_inverse_trig(expression: str, safe_globals: dict) -> Union[str, None]: """Check inverse trig function domain validity.""" for func, arg in re.findall(r"(\b\w+\b)\s*(\s*([^)]+)\s*)", expression): if func in ["asin", "acos"]: try: value = eval(arg, {"builtins": None}, safe_globals) if abs(value) > 1: return f"Error: {func}(x) is undefined for |x| > 1" except Exception as e: return f"Error: {e}" return None
def safe_evaluate(expression: str, safe_globals: dict, use_e_notation: bool) -> Union[str, Any]: """Safely evaluate expression and format result.""" try: result = eval(expression, {"builtins": None}, safe_globals) if isinstance(result, float) and abs(result) < 1e-10: result = 0.0 if isinstance(result, (int, float)): result = f"{result:.2e}" if use_e_notation else round(result, 2) return result except Exception as e: return f"Error: {e}"
def evaluate_expression(expression: str, variables: dict, use_degrees: bool = False, use_e_notation: bool = False) -> Union[float, str]: """Evaluate math expression considering modes.""" assignment_match = re.match(r'^\s*([a-zA-Z_]\w*)\s*=\s*(.+)$', expression) if assignment_match: var_name, var_expr = assignment_match.groups() safe_globals = get_safe_globals(use_degrees, variables) var_value = safe_evaluate(var_expr, safe_globals, use_e_notation) if isinstance(var_value, (int, float)): variables[var_name] = var_value return f"{var_name} = {var_value}" return var_value else: safe_globals = get_safe_globals(use_degrees, variables) expression = expression.replace("^", "**") expression = preprocess_text_functions(expression) error = validate_inverse_trig(expression, safe_globals) if error: return error return safe_evaluate(expression, safe_globals, use_e_notation)
class CalculatorGUI(QMainWindow): """PySide6-based calculator application."""
def __init__(self): super().__init__() self.use_degrees = False self.use_e_notation = False self.variables = {} self.history_entries = [] self.setup_window() self.create_widgets() self.layout_widgets() self.connect_signals() def setup_window(self) -> None: """Set main window properties.""" self.setWindowTitle("Calculator") self.setGeometry(100, 100, 1280, 720) def create_widgets(self) -> None: """Initialize GUI components.""" font = QFont() font.setPointSize(12) font.setFamily('Literata') self.entry = QLineEdit() self.entry.setFont(font) self.entry.setPlaceholderText('Enter expression') self.entry.setClearButtonEnabled(True) self.entry.returnPressed.connect(self.calculate) self.history_text = QTextEdit() self.history_text.setFont(font) self.history_text.setReadOnly(True) self.scrollbar = QScrollBar(Qt.Vertical) self.history_text.setVerticalScrollBar(self.scrollbar) self.search_button = QPushButton("🔍", self.history_text) self.search_button.setFixedSize(24, 24) self.search_button.setToolTip("Search History") self.search_button.setStyleSheet(""" QPushButton { border: none; background-color: rgba(255, 255, 255, 200); font-size: 14px; border-radius: 12px; } QPushButton:hover { background-color: rgba(0, 120, 215, 200); color: white; } """) self.search_button.clicked.connect(self.toggle_search) self.search_bar = QLineEdit(self.history_text) self.search_bar.setPlaceholderText("Search...") self.search_bar.setFixedHeight(24) self.search_bar.setVisible(False) self.search_bar.setStyleSheet(""" QLineEdit { border: 1px solid gray; border-radius: 4px; padding: 2px 4px; background-color: white; } """) self.search_bar.textChanged.connect(self.filter_history) self.search_bar.setClearButtonEnabled(True) self.function_buttons = { "Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"], "Conversions": ["lb", "kg", "K", "C", "F", "CF"], "Text": ["capitalize", "duplicates"], "Constants": ["pi", "e"], "Settings": [] } self.function_frame = QFrame() self.create_function_buttons(font) def create_function_buttons(self, font: QFont) -> None: """Create buttons for calculator functions.""" layout = QGridLayout() categories = [("Functions", 3), ("Conversions", 2), ("Text", 2), ("Constants", 2), ("Settings", 1)] starting_col = 0 for category, col_span in categories: label = QLabel(category) label.setFont(font) layout.addWidget(label, 0, starting_col, 1, col_span, Qt.AlignCenter) buttons = self.function_buttons.get(category, []) if category == "Functions": for i, func in enumerate(buttons): button = QPushButton(func) button.setFont(font) button.clicked.connect(lambda _, f=func: self.insert_function(f, False)) layout.addWidget(button, (i // 3) + 1, starting_col + (i % 3)) elif category == "Settings": self.mode_button = QPushButton("Radians") self.mode_button.setFont(font) self.mode_button.clicked.connect(self.toggle_mode) layout.addWidget(self.mode_button, 1, starting_col, 1, 1) self.e_notation_button = QPushButton("E Notation: Off") self.e_notation_button.setFont(font) self.e_notation_button.clicked.connect(self.toggle_e_notation) layout.addWidget(self.e_notation_button, 2, starting_col, 1, 1) elif category == "Conversions": for idx, func in enumerate(buttons): display_text = { "lb": "lb(kg)", "kg": "kg(lb)", "K": "K(°C)", "C": "°C(K)", "F": "F(°C)", "CF": "°C(F)" }.get(func, func) button = QPushButton(display_text) button.setFont(font) button.clicked.connect(lambda _, f=func: self.insert_function(f, False)) row, col = 1 + idx // 2, starting_col + idx % 2 layout.addWidget(button, row, col) else: num_buttons = len(buttons) num_rows = ceil(num_buttons / col_span) for idx, func in enumerate(buttons): button = QPushButton(func) button.setFont(font) button.clicked.connect(lambda _, f=func, c=(category == "Constants"): self.insert_function(f, c)) row, col = 1 + idx // col_span, starting_col + idx % col_span layout.addWidget(button, row, col) for extra in range(col_span * num_rows - num_buttons): layout.addWidget(QLabel(""), 1 + extra // col_span, starting_col + extra % col_span) starting_col += col_span self.function_frame.setLayout(layout) def layout_widgets(self) -> None: """Arrange widgets in the main window.""" central_widget = QWidget() main_layout = QVBoxLayout() main_layout.addWidget(self.entry) history_layout = QHBoxLayout() history_layout.addWidget(self.history_text) history_layout.addWidget(self.scrollbar) main_layout.addLayout(history_layout) main_layout.addWidget(self.function_frame) central_widget.setLayout(main_layout) self.setCentralWidget(central_widget) def connect_signals(self) -> None: """Connect widget signals.""" QApplication.instance().focusChanged.connect(self.on_focus_changed) def toggle_mode(self) -> None: """Toggle between degrees and radians.""" self.use_degrees = not self.use_degrees self.mode_button.setText("Degrees" if self.use_degrees else "Radians") def toggle_e_notation(self) -> None: """Toggle scientific notation for results.""" self.use_e_notation = not self.use_e_notation self.e_notation_button.setText(f"E Notation: {'On' if self.use_e_notation else 'Off'}") def insert_function(self, function: str, is_constant: bool = False) -> None: """Insert function or constant in entry.""" current_text = self.entry.text() cursor_position = self.entry.cursorPosition() if is_constant: new_text = f"{current_text[:cursor_position]}{function}" new_cursor_position = cursor_position + len(function) else: new_text = f"{current_text[:cursor_position]}{function}() {current_text[cursor_position:]}" new_cursor_position = cursor_position + len(function) + 1 self.entry.setText(new_text) self.entry.setCursorPosition(new_cursor_position) self.entry.setFocus() def calculate(self) -> None: """Evaluate entered expression.""" expression = self.entry.text().strip() if expression: result = evaluate_expression( expression, self.variables, use_degrees=self.use_degrees, use_e_notation=self.use_e_notation ) self.display_result(expression, result) self.entry.clear() def display_result(self, expression: str, result: Union[float, str]) -> None: """Show result in history.""" mode = "D" if self.use_degrees else "R" if re.match(r'^\s*[a-zA-Z_]\w*\s*=\s*.+$', expression): history_entry = f"[{mode}] {result}" else: history_entry = f"[{mode}] {expression} = {result}" self.history_entries.append(history_entry) self.refresh_history() self.history_text.verticalScrollBar().setValue( self.history_text.verticalScrollBar().maximum() ) def toggle_search(self) -> None: """Toggle search bar visibility.""" is_visible = self.search_bar.isVisible() self.search_bar.setVisible(not is_visible) if not is_visible: self.search_bar.setFocus() self.search_bar.setText("") else: self.search_bar.clear() self.update_search_bar_position() self.refresh_history() def filter_history(self, text: str) -> None: """Filter history based on search input.""" self.refresh_history(text) def refresh_history(self, filter_text: str = "") -> None: """Refresh history view with optional filtering.""" self.history_text.clear() for entry in self.history_entries: if filter_text.lower() in entry.lower(): self.history_text.append(entry) def resizeEvent(self, event) -> None: """Handle window resize events.""" super().resizeEvent(event) self.update_search_bar_position() def update_search_bar_position(self) -> None: """Reposition search button and bar.""" margin_right = 5 margin_top = 5 spacing = 5 history_width = self.history_text.viewport().width() self.search_button.move( history_width - self.search_button.width() - margin_right, margin_top ) if self.search_bar.isVisible(): search_bar_width = int(history_width * 0.25) if search_bar_width + self.search_button.width() + spacing > history_width: search_bar_width = history_width - self.search_button.width() - spacing - margin_right self.search_bar.setFixedWidth(search_bar_width) self.search_bar.move( self.search_button.x() - self.search_bar.width() - spacing, self.search_button.y() ) def on_focus_changed(self, old: QWidget, new: QWidget) -> None: """Auto-hide search if focus is lost.""" if self.search_bar.isVisible() and not self.search_bar.text().strip() and new != self.search_bar: self.toggle_search() def showEvent(self, event) -> None: """Position search button on showing the window.""" super().showEvent(event) self.update_search_bar_position()def main() -> None: """Start the calculator application.""" app = QApplication([]) calculator = CalculatorGUI() calculator.show() app.exec()
if name == "main": main()
- Assistant
Your Python 3.12 calculator application is well-structured and functional. However, there are several areas where the Don't Repeat Yourself (DRY) principle can be better adhered to. Eliminating these redundancies can make your code more maintainable, concise, and less error-prone. Below is a detailed analysis of the redundancies along with suggestions for refactoring.
1. Redundant Import Statements
Issue:
You are importing the entire
mathmodule and specific functions from it separately:import math from math import radians, pi, e, sqrt, log10, log, ceilThis redundancy can lead to confusion and unnecessarily increases the namespace.
Solution:
Choose one of the following approaches:
-
Option 1: Import the entire
mathmodule and access functions using the module prefix.import math # Usage: math.radians(x) math.pi -
Option 2: Import only the necessary functions if the module prefix isn't needed elsewhere.
from math import radians, pi, e, sqrt, log10, log, ceil # Usage: radians(x) pi
Recommendation: If you're frequently using the module prefix elsewhere in your code (e.g., in
get_safe_globals), it's cleaner to import the entire module.2. Conversion Functions Redundancy
Issue:
You have multiple functions for unit conversions that follow a similar pattern:
def kilograms_to_pounds(kg: float) -> float: return kg / 0.45359237 def pounds_to_kilograms(lb: float) -> float: return lb * 0.45359237 def celsius_to_kelvin(c: float) -> float: return c + 273.15 def kelvin_to_celsius(k: float) -> float: return k - 273.15 def celsius_to_fahrenheit(c: float) -> float: return c * 9 / 5 + 32 def fahrenheit_to_celsius(f: float) -> float: return (f - 32) * 5 / 9Solution:
Implement a more generic conversion function that can handle different types of conversions using a mapping or configuration.
Example: Using a Conversion Dictionary
# Define a conversion mapping CONVERSIONS = { 'kg_to_lb': lambda kg: kg / 0.45359237, 'lb_to_kg': lambda lb: lb * 0.45359237, 'C_to_K': lambda c: c + 273.15, 'K_to_C': lambda k: k - 273.15, 'C_to_F': lambda c: c * 9 / 5 + 32, 'F_to_C': lambda f: (f - 32) * 5 / 9, } def convert_units(conversion_type: str, value: float) -> float: try: return CONVERSIONS[conversion_type](value) except KeyError: raise ValueError(f"Unsupported conversion type: {conversion_type}")Usage:
convert_units('kg_to_lb', 10) # Converts 10 kilograms to pounds convert_units('C_to_F', 25) # Converts 25 Celsius to FahrenheitBenefits:
- Scalability: Easily add new conversions without defining additional functions.
- Maintainability: Centralized conversion logic makes it easier to manage.
- Reduced Redundancy: Eliminates multiple functions that perform similar tasks.
3. Button Creation in
create_function_buttonsIssue:
The
create_function_buttonsmethod contains repetitive code for creating buttons across different categories. Each category has its own loop and handling logic, leading to duplicated patterns.if category == "Functions": for i, func in enumerate(buttons): button = QPushButton(func) button.setFont(font) button.clicked.connect(lambda _, f=func: self.insert_function(f, False)) layout.addWidget(button, (i // 3) + 1, starting_col + (i % 3)) elif category == "Settings": # Similar repetitive code elif category == "Conversions": # Similar repetitive code else: # Similar repetitive codeSolution:
Abstract the button creation logic into a helper method. This method can handle common behaviors like setting the font, connecting signals, and adding to the layout.
Refactored
create_function_buttonsMethod:def create_function_buttons(self, font: QFont) -> None: """Create buttons for calculator functions.""" layout = QGridLayout() categories = [("Functions", 3), ("Conversions", 2), ("Text", 2), ("Constants", 2), ("Settings", 1)] starting_col = 0 for category, col_span in categories: label = QLabel(category) label.setFont(font) layout.addWidget(label, 0, starting_col, 1, col_span, Qt.AlignCenter) buttons = self.function_buttons.get(category, []) if category == "Settings": self._add_setting_buttons(layout, font, starting_col) else: self._add_category_buttons(layout, font, category, buttons, starting_col, col_span) starting_col += col_span self.function_frame.setLayout(layout) def _add_setting_buttons(self, layout, font, starting_col): """Add setting buttons.""" self.mode_button = QPushButton("Radians") self.mode_button.setFont(font) self.mode_button.clicked.connect(self.toggle_mode) layout.addWidget(self.mode_button, 1, starting_col, 1, 1) self.e_notation_button = QPushButton("E Notation: Off") self.e_notation_button.setFont(font) self.e_notation_button.clicked.connect(self.toggle_e_notation) layout.addWidget(self.e_notation_button, 2, starting_col, 1, 1) def _add_category_buttons(self, layout, font, category, buttons, starting_col, col_span): """Add buttons for a given category.""" if category == "Functions" or category == "Conversions" or category == "Constants" or category == "Text": for idx, func in enumerate(buttons): if category == "Conversions": display_text = { "lb": "lb(kg)", "kg": "kg(lb)", "K": "K(°C)", "C": "°C(K)", "F": "F(°C)", "CF": "°C(F)" }.get(func, func) else: display_text = func button = QPushButton(display_text) button.setFont(font) # Determine if it's a constant is_constant = category == "Constants" button.clicked.connect(lambda _, f=func, c=is_constant: self.insert_function(f, c)) row = 1 + idx // col_span col = starting_col + idx % col_span layout.addWidget(button, row, col) # Fill the remaining grid with empty labels to maintain layout num_buttons = len(buttons) num_rows = ceil(num_buttons / col_span) for extra in range(col_span * num_rows - num_buttons): layout.addWidget(QLabel(""), 1 + extra // col_span, starting_col + extra % col_span)Benefits:
- Reduced Redundancy: Common button creation logic is centralized.
- Improved Readability: The main method is cleaner and easier to understand.
- Ease of Maintenance: Changes to button creation need to be made in only one place.
4. Similar Stylesheet Strings
Issue:
Stylesheets for widgets like
search_buttonandsearch_barare defined inline with possible repeated patterns.self.search_button.setStyleSheet(""" QPushButton { border: none; background-color: rgba(255, 255, 255, 200); font-size: 14px; border-radius: 12px; } QPushButton:hover { background-color: rgba(0, 120, 215, 200); color: white; } """) self.search_bar.setStyleSheet(""" QLineEdit { border: 1px solid gray; border-radius: 4px; padding: 2px 4px; background-color: white; } """)Solution:
Define common styles as class constants or use helper methods to apply styles. This approach avoids duplicating stylesheet strings across different widgets.
Example: Using Class Constants
class CalculatorGUI(QMainWindow): """PySide6-based calculator application.""" BUTTON_STYLE = """ QPushButton { border: none; background-color: rgba(255, 255, 255, 200); font-size: 14px; border-radius: 12px; } QPushButton:hover { background-color: rgba(0, 120, 215, 200); color: white; } """ SEARCH_BAR_STYLE = """ QLineEdit { border: 1px solid gray; border-radius: 4px; padding: 2px 4px; background-color: white; } """ def create_widgets(self) -> None: """Initialize GUI components.""" # ... other widget initializations ... self.search_button.setStyleSheet(self.BUTTON_STYLE) self.search_bar.setStyleSheet(self.SEARCH_BAR_STYLE)Benefits:
- Consistency: Ensures a uniform look across similar widgets.
- Maintainability: Easier to update styles in one place rather than multiple locations.
5. Lambda Function Usage in Signal Connections
Issue:
Using
lambdain signal connections can sometimes lead to late binding issues or make the code harder to debug.button.clicked.connect(lambda _, f=func: self.insert_function(f, False))Solution:
Use the
functools.partialfunction to create callbacks with pre-filled arguments. This approach is cleaner and avoids potential lambda-related issues.Example:
from functools import partial button.clicked.connect(partial(self.insert_function, func, False))Refactored Button Connection:
from functools import partial def _add_category_buttons(self, layout, font, category, buttons, starting_col, col_span): """Add buttons for a given category.""" if category == "Functions" or category == "Conversions" or category == "Constants" or category == "Text": for idx, func in enumerate(buttons): if category == "Conversions": display_text = { "lb": "lb(kg)", "kg": "kg(lb)", "K": "K(°C)", "C": "°C(K)", "F": "F(°C)", "CF": "°C(F)" }.get(func, func) else: display_text = func button = QPushButton(display_text) button.setFont(font) # Determine if it's a constant is_constant = category == "Constants" # Use functools.partial instead of lambda button.clicked.connect(partial(self.insert_function, func, is_constant)) row = 1 + idx // col_span col = starting_col + idx % col_span layout.addWidget(button, row, col) # Fill the remaining grid with empty labels to maintain layout num_buttons = len(buttons) num_rows = ceil(num_buttons / col_span) for extra in range(col_span * num_rows - num_buttons): layout.addWidget(QLabel(""), 1 + extra // col_span, starting_col + extra % col_span)Benefits:
- Clarity:
partialexplicitly shows which arguments are being passed. - Safety: Avoids common pitfalls associated with
lambdafunctions in loops.
6. Repeated Regular Expressions
Issue:
Regular expressions are used in multiple functions like
preprocess_text_functions,validate_inverse_trig, andevaluate_expression. If these regex patterns are reused or similar, defining them as constants can reduce duplication.re.sub(r'\b(capitalize|duplicates)\s*\(\s*([^)]+)\s*\)', add_quotes, expression) re.findall(r"(\b\w+\b)\s*\(\s*([^)]+)\s*\)", expression) re.match(r'^\s*([a-zA-Z_]\w*)\s*=\s*(.+)$', expression)Solution:
Define regex patterns as class constants or module-level constants.
Example:
# At the top of the module ASSIGNMENT_PATTERN = re.compile(r'^\s*([a-zA-Z_]\w*)\s*=\s*(.+)$') FUNCTION_CALL_PATTERN = re.compile(r'\b(capitalize|duplicates)\s*\(\s*([^)]+)\s*\)') FIND_FUNCTIONS_PATTERN = re.compile(r"(\b\w+\b)\s*\(\s*([^)]+)\s*\)") # Usage in functions assignment_match = ASSIGNMENT_PATTERN.match(expression) preprocessed_expression = FUNCTION_CALL_PATTERN.sub(add_quotes, expression) for func, arg in FIND_FUNCTIONS_PATTERN.findall(expression): # ...Benefits:
- Performance: Compiling regex patterns once can improve performance, especially if used frequently.
- Maintainability: Easier to manage and update patterns in a centralized location.
- Readability: Named constants make the purpose of each pattern clearer.
7. Handling Function Insertion in Entry
Issue:
The
insert_functionmethod differentiates between inserting constants and functions, leading to similar but slightly different logic.if is_constant: new_text = f"{current_text[:cursor_position]}{function}" new_cursor_position = cursor_position + len(function) else: new_text = f"{current_text[:cursor_position]}{function}() {current_text[cursor_position:]}" new_cursor_position = cursor_position + len(function) + 1Solution:
Abstract the insertion logic to handle different cases more elegantly, possibly by using formats or helper methods.
Example:
def insert_function(self, function: str, is_constant: bool = False) -> None: """Insert function or constant in entry.""" current_text = self.entry.text() cursor_position = self.entry.cursorPosition() insertion = function if is_constant else f"{function}() " new_cursor_position = cursor_position + len(function) + (0 if is_constant else 3) # Adjust for '() ' new_text = f"{current_text[:cursor_position]}{insertion}{current_text[cursor_position:]}" self.entry.setText(new_text) self.entry.setCursorPosition(new_cursor_position) self.entry.setFocus()Benefits:
- Clarity: Clearly separates the insertion logic based on the type.
- Flexibility: Easier to add more cases if needed in the future.
8. Consolidating Mode Toggles
Issue:
You have separate methods for toggling degrees/radians and E-notation:
def toggle_mode(self) -> None: self.use_degrees = not self.use_degrees self.mode_button.setText("Degrees" if self.use_degrees else "Radians") def toggle_e_notation(self) -> None: self.use_e_notation = not self.use_e_notation self.e_notation_button.setText(f"E Notation: {'On' if self.use_e_notation else 'Off'}")While these methods are simple, they follow a similar pattern and can be generalized.
Solution:
Create a generic toggle method that can handle different toggles based on parameters.
Example:
def toggle_setting(self, setting_name: str) -> None: if setting_name == "mode": self.use_degrees = not self.use_degrees self.mode_button.setText("Degrees" if self.use_degrees else "Radians") elif setting_name == "e_notation": self.use_e_notation = not self.use_e_notation self.e_notation_button.setText(f"E Notation: {'On' if self.use_e_notation else 'Off'}") # Connect signals using partial self.mode_button.clicked.connect(partial(self.toggle_setting, "mode")) self.e_notation_button.clicked.connect(partial(self.toggle_setting, "e_notation"))Benefits:
- Reduced Redundancy: Single method handles multiple toggles.
- Scalability: Easier to add more toggles without creating new methods.
9. Handling Search Functionality
Issue:
The search functionality involves multiple methods (
toggle_search,filter_history,refresh_history,update_search_bar_position, etc.) that interact in a complex manner. While not strictly violating DRY, the interconnectedness can lead to maintainability challenges.Solution:
Encapsulate search-related functionalities into a separate class or component. This modular approach separates concerns and makes the codebase cleaner.
Example:
class SearchWidget(QWidget): """Encapsulates search bar and button functionality.""" def __init__(self, parent, on_search): super().__init__(parent) self.on_search = on_search self.setup_ui() def setup_ui(self): self.search_button = QPushButton("🔍") self.search_button.setFixedSize(24, 24) self.search_button.setToolTip("Search History") self.search_button.setStyleSheet(self.BUTTON_STYLE) self.search_button.clicked.connect(self.toggle_search) self.search_bar = QLineEdit() self.search_bar.setPlaceholderText("Search...") self.search_bar.setFixedHeight(24) self.search_bar.setVisible(False) self.search_bar.setStyleSheet(self.SEARCH_BAR_STYLE) self.search_bar.textChanged.connect(self.on_search) self.search_bar.setClearButtonEnabled(True) layout = QHBoxLayout() layout.addWidget(self.search_button) layout.addWidget(self.search_bar) self.setLayout(layout) def toggle_search(self): is_visible = self.search_bar.isVisible() self.search_bar.setVisible(not is_visible) if not is_visible: self.search_bar.setFocus() self.search_bar.setText("") else: self.search_bar.clear()Integration in
CalculatorGUI:def create_widgets(self) -> None: """Initialize GUI components.""" # ... other widget initializations ... self.search_widget = SearchWidget(self.history_text, self.filter_history) # Add search_widget to the layout as neededBenefits:
- Separation of Concerns: Isolates search functionality from the main GUI logic.
- Reusability: The
SearchWidgetcan be reused in other parts of the application or future projects. - Maintainability: Easier to manage and update search-related features without affecting other components.
10. Using Data Classes for Configuration
Issue:
Your
get_safe_globalsfunction manually constructs asafe_globalsdictionary. Managing this manually can lead to errors and make the code harder to extend.Solution:
Use Python's
dataclassto define configurations or use more structured approaches to buildsafe_globals.Example:
from dataclasses import dataclass, field @dataclass class SafeGlobalsConfig: use_degrees: bool variables: dict = field(default_factory=dict) def build_globals(self) -> dict: trig_funcs = {'sin', 'cos', 'tan', 'asin', 'acos', 'atan'} safe_globals = { "sqrt": math.sqrt, "log": math.log10, "ln": math.log, "pi": math.pi, "e": math.e, "lb": CONVERSIONS['kg_to_lb'], "kg": CONVERSIONS['lb_to_kg'], "C": CONVERSIONS['K_to_C'], "K": CONVERSIONS['C_to_K'], "F": CONVERSIONS['C_to_F'], "CF": CONVERSIONS['F_to_C'], "capitalize": capitalize_sentence, "duplicates": remove_duplicates, } for func in trig_funcs: safe_globals[func] = partial(convert_angle, getattr(math, func), use_degrees=self.use_degrees) safe_globals.update(self.variables) return safe_globalsUsage in
evaluate_expression:def evaluate_expression(expression: str, variables: dict, use_degrees: bool = False, use_e_notation: bool = False) -> Union[float, str]: config = SafeGlobalsConfig(use_degrees=use_degrees, variables=variables) safe_globals = config.build_globals() # ... rest of the function ...Benefits:
- Structured Configuration: Clear separation of configuration and execution logic.
- Easier Extensions: Adding new configurations becomes straightforward.
- Improved Readability: More descriptive and organized handling of globals.
Conclusion
By addressing these redundancies and refactoring the code accordingly, you not only adhere to the DRY principle but also enhance the overall quality of your application. Here’s a summary of the key refactoring steps:
- Consolidate Import Statements: Choose between module imports or specific function imports to reduce namespace clutter.
- Generalize Conversion Functions: Use a mapping or generic functions to handle unit conversions.
- Abstract Button Creation Logic: Create helper methods or use partials to handle repetitive button setup.
- Centralize Stylesheet Definitions: Define styles as constants or use helper methods to apply them consistently.
- Use
functools.partialInstead of Lambdas: Improve readability and avoid common pitfalls with lambda functions. - Define Regex Patterns as Constants: Compile and name regex patterns for better performance and clarity.
- Modularize Search Functionality: Encapsulate search-related widgets and logic into separate classes or components.
- Employ Data Classes for Configurations: Use structured approaches like data classes to manage configurations and globals.
Implementing these changes will make your codebase cleaner, more efficient, and easier to maintain.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.