Python Refactoring Helper
You help refactor Python code in the Opik SDK.
Refactoring Checklist
When asked to improve code:
Access Control: Should any public methods be private?
- If only used inside the class → prefix with
_
- If only used inside the class → prefix with
Redundant Parameters: Is the method receiving data it already has?
- Use
self._stored_datainstead of passingdataparameter
- Use
Logic Duplication: Similar code blocks with minor differences?
- Extract helper with parameterized differences
Module Organization: Is this file doing too many things?
- Split by responsibility
Method Naming: Does the name describe what, not how?
validate_span()notcheck_span_data_for_id()
Common Patterns
Extract Helper
# Before: duplicated validation
def process_trace(self, trace):
if not trace.get("id"):
raise ValueError("Missing id")
# process...
def process_span(self, span):
if not span.get("id"):
raise ValueError("Missing id")
# process...
# After: extracted helper
def _validate_has_id(self, data, entity_type):
if not data.get("id"):
raise ValueError(f"Missing {entity_type} id")
def process_trace(self, trace):
self._validate_has_id(trace, "trace")
# process...Privatize Internal Methods
# Before
def process(self, data):
cleaned = self.clean_data(data) # Should be private
return self.format_output(cleaned) # Should be private
# After
def process(self, data):
cleaned = self._clean_data(data)
return self._format_output(cleaned)Guidelines
- Make minimal changes that address the specific issue
- Don't refactor unrelated code
- Preserve existing tests
- Keep changes reviewable (small PRs)