Skip to content

Commit e02a491

Browse files
author
Ryan Story
committed
Fix all mypy type errors in CI-failing files
- Add type annotations for results dictionaries in proc_print, proc_sql, proc_language - Add None checks for self.generator in proc_language methods - Fix notebook_interpreter return types with type: ignore comments - Fix kernel signature mismatches by adding missing parameters - Add Optional type annotation for self.interpreter in statlang_kernel - Add type guards for all self.interpreter usages All originally failing files now pass mypy type checking. All tests still pass.
1 parent af5cdd9 commit e02a491

6 files changed

Lines changed: 51 additions & 13 deletions

File tree

stat_lang/kernel/statlang_kernel.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ def __init__(self, **kwargs):
6060
logger.info("=" * 80)
6161

6262
super().__init__(**kwargs)
63+
self.interpreter: Optional[SASInterpreter] = None
6364
try:
6465
self.interpreter = SASInterpreter()
6566
# Kernel base class initializes execution_count, but ensure it starts at 0
@@ -76,7 +77,7 @@ def __init__(self, **kwargs):
7677
print(f"Warning: Failed to initialize interpreter: {e}")
7778
self.interpreter = None
7879

79-
def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False):
80+
def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False, *, cell_meta=None, cell_id=None):
8081
"""Execute StatLang code in the kernel."""
8182

8283
logger.info(f"do_execute called with code: {repr(code[:100])}...")
@@ -135,6 +136,8 @@ def do_execute(self, code, silent, store_history=True, user_expressions=None, al
135136
self.error_buffer = io.StringIO()
136137

137138
# Record datasets before execution
139+
if self.interpreter is None:
140+
return {'status': 'error', 'ename': 'InterpreterError', 'evalue': 'Interpreter not initialized'}
138141
datasets_before = set(self.interpreter.data_sets.keys())
139142
logger.info(f"Datasets before execution: {datasets_before}")
140143

@@ -176,7 +179,8 @@ def do_execute(self, code, silent, store_history=True, user_expressions=None, al
176179
self._send_datasets_display(datasets)
177180
else:
178181
# Reset the flag for next execution
179-
self.interpreter._suppress_dataset_display = False
182+
if self.interpreter is not None:
183+
self.interpreter._suppress_dataset_display = False
180184

181185
logger.info("Returning successful execution result")
182186
# Increment execution count AFTER successful execution
@@ -250,7 +254,7 @@ def do_complete(self, code, cursor_pos):
250254
'status': 'ok'
251255
}
252256

253-
def do_inspect(self, code, cursor_pos, detail_level=0):
257+
def do_inspect(self, code, cursor_pos, detail_level=0, omit_sections=()):
254258
"""Provide code inspection/hover information."""
255259
# Get the word at cursor position
256260
text_before_cursor = code[:cursor_pos]
@@ -281,6 +285,8 @@ def do_inspect(self, code, cursor_pos, detail_level=0):
281285

282286
def _get_datasets_info(self):
283287
"""Get information about datasets created in the interpreter."""
288+
if self.interpreter is None:
289+
return {}
284290
datasets = {}
285291
for name, df in self.interpreter.data_sets.items():
286292
datasets[name] = {
@@ -294,6 +300,8 @@ def _get_datasets_info(self):
294300

295301
def _get_new_datasets_info(self, datasets_before):
296302
"""Get information about datasets created in the current execution."""
303+
if self.interpreter is None:
304+
return {}
297305
datasets = {}
298306
current_datasets = set(self.interpreter.data_sets.keys())
299307
new_datasets = current_datasets - datasets_before

stat_lang/kernel/working_kernel.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def __init__(self, **kwargs):
3535
self.error_buffer = io.StringIO()
3636
self.datasets_before_execution = set()
3737

38-
def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False):
38+
def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False, *, cell_meta=None, cell_id=None):
3939
"""Execute StatLang code in the kernel."""
4040

4141
# Skip empty cells
@@ -151,7 +151,7 @@ def do_complete(self, code, cursor_pos):
151151
'status': 'ok'
152152
}
153153

154-
def do_inspect(self, code, cursor_pos, detail_level=0):
154+
def do_inspect(self, code, cursor_pos, detail_level=0, omit_sections=()):
155155
"""Provide code inspection/hover information."""
156156
# Get the word at cursor position
157157
text_before_cursor = code[:cursor_pos]

stat_lang/notebook_interpreter.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def __init__(self):
2323
self.output_buffer = io.StringIO()
2424
self.error_buffer = io.StringIO()
2525

26-
def run_code(self, sas_code: str) -> Dict[str, Any]:
26+
def run_code(self, sas_code: str) -> Dict[str, Any]: # type: ignore[override]
2727
"""
2828
Run SAS code and return structured results for notebook display.
2929
@@ -91,7 +91,7 @@ def _get_summary_stats(self, df: pd.DataFrame) -> Dict[str, Any]:
9191
if len(numeric_cols) == 0:
9292
return {}
9393

94-
return df[numeric_cols].describe().to_dict()
94+
return df[numeric_cols].describe().to_dict() # type: ignore[no-any-return]
9595

9696
def _get_proc_results(self) -> List[Dict[str, Any]]:
9797
"""Get results from PROC procedures executed in this session."""
@@ -168,11 +168,11 @@ def export_dataset(self, name: str, format: str = 'json') -> str:
168168
return f"Dataset {name} not found"
169169

170170
if format == 'json':
171-
return df.to_json(orient='records', indent=2)
171+
return str(df.to_json(orient='records', indent=2))
172172
elif format == 'csv':
173-
return df.to_csv(index=False)
173+
return str(df.to_csv(index=False))
174174
elif format == 'html':
175-
return df.to_html(index=False, classes='table table-striped')
175+
return str(df.to_html(index=False, classes='table table-striped'))
176176
else:
177177
return f"Unsupported format: {format}"
178178

stat_lang/procs/proc_language.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def execute(self, data: pd.DataFrame, proc_info: ProcStatement, dataset_manager=
5757
Returns:
5858
Dictionary containing results and output data
5959
"""
60-
results = {
60+
results: Dict[str, Any] = {
6161
'output_text': [],
6262
'output_data': None
6363
}
@@ -122,6 +122,11 @@ def execute(self, data: pd.DataFrame, proc_info: ProcStatement, dataset_manager=
122122

123123
def _generate_text(self, prompt: str, model: str) -> Dict[str, Any]:
124124
"""Generate text using the Hugging Face model."""
125+
if self.generator is None:
126+
return {
127+
'output': ["ERROR: Language model not initialized."],
128+
'data': None
129+
}
125130
try:
126131
# Generate text using the pipeline
127132
result = self.generator(
@@ -161,6 +166,11 @@ def _generate_text(self, prompt: str, model: str) -> Dict[str, Any]:
161166

162167
def _question_answer(self, question: str, context: str, model: str) -> Dict[str, Any]:
163168
"""Answer questions using the model."""
169+
if self.generator is None:
170+
return {
171+
'output': ["ERROR: Language model not initialized."],
172+
'data': None
173+
}
164174
try:
165175
# For Q&A, we'll use text generation with a structured prompt
166176
if context:
@@ -208,6 +218,11 @@ def _question_answer(self, question: str, context: str, model: str) -> Dict[str,
208218

209219
def _summarize_text(self, text: str, model: str) -> Dict[str, Any]:
210220
"""Summarize text using the model."""
221+
if self.generator is None:
222+
return {
223+
'output': ["ERROR: Language model not initialized."],
224+
'data': None
225+
}
211226
try:
212227
summary_prompt = f"Summarize the following text:\n\n{text}\n\nSummary:"
213228

@@ -249,6 +264,11 @@ def _summarize_text(self, text: str, model: str) -> Dict[str, Any]:
249264

250265
def _analyze_text(self, text: str, model: str) -> Dict[str, Any]:
251266
"""Analyze text using the model."""
267+
if self.generator is None:
268+
return {
269+
'output': ["ERROR: Language model not initialized."],
270+
'data': None
271+
}
252272
try:
253273
analysis_prompt = f"Analyze the following text and provide insights:\n\n{text}\n\nAnalysis:"
254274

@@ -290,6 +310,11 @@ def _analyze_text(self, text: str, model: str) -> Dict[str, Any]:
290310

291311
def _summarize_data(self, data: pd.DataFrame, var_vars: List[str], prompt: str, model: str) -> Dict[str, Any]:
292312
"""Summarize data using the model."""
313+
if self.generator is None:
314+
return {
315+
'output': ["ERROR: Language model not initialized."],
316+
'data': None
317+
}
293318
try:
294319
# Create a text description of the data
295320
data_desc = f"Dataset with {len(data)} rows and {len(data.columns)} columns."
@@ -337,6 +362,11 @@ def _summarize_data(self, data: pd.DataFrame, var_vars: List[str], prompt: str,
337362

338363
def _analyze_data(self, data: pd.DataFrame, var_vars: List[str], prompt: str, model: str) -> Dict[str, Any]:
339364
"""Analyze data using the model."""
365+
if self.generator is None:
366+
return {
367+
'output': ["ERROR: Language model not initialized."],
368+
'data': None
369+
}
340370
try:
341371
# Create a text description of the data
342372
data_desc = f"Dataset with {len(data)} rows and {len(data.columns)} columns."

stat_lang/procs/proc_print.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def execute(self, data: pd.DataFrame, proc_info: ProcStatement, dataset_manager=
3131
Returns:
3232
Dictionary containing results and output data
3333
"""
34-
results = {
34+
results: Dict[str, Any] = {
3535
'output_text': [],
3636
'output_data': None
3737
}

stat_lang/procs/proc_sql.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def execute(self, data: pd.DataFrame, proc_info: ProcStatement, dataset_manager=
4040
Returns:
4141
Dictionary containing results and output data
4242
"""
43-
results = {
43+
results: Dict[str, Any] = {
4444
'output_text': [],
4545
'output_data': None
4646
}

0 commit comments

Comments
 (0)