Skip to content

Commit 5e55a38

Browse files
authored
Lint print breakpoint (#1267)
1 parent 41ac70b commit 5e55a38

28 files changed

Lines changed: 114 additions & 85 deletions

.pre-commit-config.yaml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,20 @@ repos:
2323
hooks:
2424
- id: isort
2525
name: isort (python)
26+
- repo: https://github.com/pre-commit/pygrep-hooks
27+
rev: v1.10.0
28+
hooks:
29+
- id: python-no-log-warn
30+
- id: python-use-type-annotations
31+
# Custom hook to catch breakpoint() calls
32+
- repo: local
33+
hooks:
34+
- id: no-breakpoint
35+
name: No breakpoint() calls
36+
entry: breakpoint\(
37+
language: pygrep
38+
files: \.py$
39+
types: [python]
2640
- repo: https://github.com/shssoichiro/oxipng
2741
rev: v9.1.3
2842
hooks:

lumen/ai/llm.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -345,8 +345,8 @@ def warmup(cls, model_kwargs: dict | None):
345345
return
346346

347347
from huggingface_hub import hf_hub_download
348-
print(f"{cls.__name__} provider is downloading following models:\n\n{json.dumps(huggingface_models, indent=2)}")
349-
for model, kwargs in model_kwargs.items():
348+
print(f"{cls.__name__} provider is downloading following models:\n\n{json.dumps(huggingface_models, indent=2)}") # noqa: T201
349+
for kwargs in model_kwargs.values():
350350
repo = kwargs.get('repo', kwargs.get('repo_id'))
351351
model_file = kwargs.get('model_file')
352352
hf_hub_download(repo, model_file)
@@ -703,11 +703,11 @@ async def run_client(self, model_spec: str | dict, messages: list[Message], **kw
703703
"""Override to handle Gemini-specific message format conversion."""
704704
try:
705705
from google.genai.types import GenerateContentConfig
706-
except ImportError:
706+
except ImportError as exc:
707707
raise ImportError(
708708
"Please install the `google-generativeai` package to use Google AI models. "
709709
"You can install it with `pip install -U google-genai`."
710-
)
710+
) from exc
711711

712712
client = await self.get_client(model_spec, **kwargs)
713713

lumen/ai/schemas.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def _generate_context(self, truncate: bool | None = None) -> str:
8181
original_indices = list(range(len(cols_to_show)))
8282
show_ellipsis = False
8383

84-
for i, (col, orig_idx) in enumerate(zip(cols_to_show, original_indices)):
84+
for i, (col, orig_idx) in enumerate(zip(cols_to_show, original_indices, strict=False)):
8585
if show_ellipsis and i == len(cols_to_show) // 2:
8686
context += "...\n"
8787

@@ -188,7 +188,7 @@ def _generate_context(self, truncate: bool | None = None) -> str:
188188
original_indices = list(range(len(cols_to_show)))
189189
show_ellipsis = False
190190

191-
for i, (col, orig_idx) in enumerate(zip(cols_to_show, original_indices)):
191+
for i, (col, orig_idx) in enumerate(zip(cols_to_show, original_indices, strict=False)):
192192
if show_ellipsis and i == len(cols_to_show) // 2:
193193
context += "...\n"
194194

lumen/ai/tools.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -529,7 +529,7 @@ def _format_results_for_refinement(self, results: list[dict[str, Any]]) -> str:
529529
Formatted description of document results
530530
"""
531531
formatted_results = []
532-
for i, result in enumerate(results):
532+
for _i, result in enumerate(results):
533533
metadata = result.get('metadata', {})
534534
filename = metadata.get('filename', 'Unknown document')
535535
text_preview = truncate_string(result.get('text', ''), max_length=150)
@@ -670,7 +670,7 @@ def _format_results_for_refinement(self, results: list[dict[str, Any]]) -> str:
670670
Formatted description of table results
671671
"""
672672
formatted_results = []
673-
for i, result in enumerate(results):
673+
for _i, result in enumerate(results):
674674
source_name = result['metadata'].get("source", "unknown")
675675
table_name = result['metadata'].get("table_name", "unknown")
676676
text = result["text"]

lumen/ai/translate.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -510,8 +510,8 @@ def pydantic_to_param_instance(model: BaseModel) -> param.Parameterized:
510510
try:
511511
parameterized_class = model._parameterized # type: ignore
512512
valid_param_names = set(parameterized_class.param)
513-
except AttributeError:
514-
raise ValueError("The provided model does not have a _parameterized attribute, indicating it was not created from a param.Parameterized class.")
513+
except AttributeError as exc:
514+
raise ValueError("The provided model does not have a _parameterized attribute, indicating it was not created from a param.Parameterized class.") from exc
515515

516516
kwargs = {}
517517
for key, value in model:
@@ -590,7 +590,7 @@ def function_to_model(function: FunctionType, skipped: list[str] | None = None)
590590
fields: dict[str, tuple[Any, FieldInfo]] = {} # Changed core_schema.TypedDictField to tuple[Any, FieldInfo] for create_model
591591
description, field_descriptions = doc_descriptions(function, sig)
592592

593-
for index, (name, p) in enumerate(sig.parameters.items()):
593+
for _index, (name, p) in enumerate(sig.parameters.items()):
594594
if p.annotation is sig.empty:
595595
annotation = Any
596596
else:

lumen/ai/ui.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ def __init__(
192192
self._notebook_export, *(
193193
Button(
194194
name=label, button_type='primary',
195-
on_click=lambda _: e(self.interface),
195+
on_click=lambda _, e=e: e(self.interface),
196196
stylesheets=['.bk-btn { padding: 4.5px 6px;']
197197
)
198198
for label, e in self.export_functions.items()
@@ -591,7 +591,7 @@ def _set_conversation(self, conversation: list[Any]):
591591
async def _cleanup_explorations(self, event):
592592
if len(event.new) <= len(event.old):
593593
return
594-
for i, (old, new) in enumerate(zip(event.old, event.new)):
594+
for i, (old, new) in enumerate(zip(event.old, event.new, strict=False)):
595595
if old is new:
596596
continue
597597
self._contexts.pop(i)

lumen/ai/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ async def get_schema(
318318
count = schema.pop("__len__", None)
319319

320320
if not include_type:
321-
for field, spec in schema.items():
321+
for spec in schema.values():
322322
if "type" in spec:
323323
spec.pop("type")
324324

@@ -387,7 +387,7 @@ async def get_schema(
387387
continue
388388

389389
# Format any other numeric values in the schema
390-
for field, spec in schema.items():
390+
for spec in schema.values():
391391
for key, value in spec.items():
392392
if isinstance(value, (int, float)) and key not in ['type']:
393393
spec[key] = format_float(value)

lumen/ai/vector_store.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -167,10 +167,6 @@ async def _generate_context(self, document: str, chunk: str, previous_context: s
167167
if isinstance(response, str):
168168
return response
169169
else:
170-
print(
171-
f"Used: {response.usage.prompt_tokens} total tokens ({response.usage.prompt_tokens_details.cached_tokens} cached) and output {response.usage.completion_tokens}"
172-
)
173-
print("\n\n")
174170
return response.choices[0].message.content
175171

176172
@pn_cache
@@ -1059,7 +1055,7 @@ def _setup_database(self, embedding_dim: int) -> None:
10591055
"class": self.embeddings.__class__.__module__ + "." + self.embeddings.__class__.__name__,
10601056
"params": {}
10611057
}
1062-
for param_name, param_obj in self.embeddings.param.objects().items():
1058+
for param_name, _param_obj in self.embeddings.param.objects().items():
10631059
if param_name not in ['name']:
10641060
value = getattr(self.embeddings, param_name)
10651061
if isinstance(value, (str, int, float, bool, list, dict)) or value is None:

lumen/ai/views.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ async def render(self):
164164
value=True, name="Rendering component...", height=50, width=50
165165
)
166166

167-
if self.render_output and (self.active != (len(self._main)-1)) or self.spec is None:
167+
if (self.render_output and (self.active != (len(self._main)-1))) or self.spec is None:
168168
return
169169

170170
if self.spec in self._last_output:
@@ -235,8 +235,8 @@ def process_error(err):
235235
# $.encoding.x.sort: '-host_count' is not one of ..
236236
#$.encoding.x: 'value' is a required property
237237
if (
238-
last_path != path
239-
and last_path.split(path)[-1].count(".") <= 1
238+
(last_path != path
239+
and last_path.split(path)[-1].count(".") <= 1)
240240
or path in rejected_paths
241241
):
242242
rejected_paths.add(path)
@@ -271,7 +271,7 @@ def _validate_spec(cls, spec):
271271
spec_copy.pop("params", None)
272272
vega_lite_validator.validate(spec_copy)
273273
except ValidationError as e:
274-
raise ValidationError(cls._format_validation_error(e))
274+
raise ValidationError(cls._format_validation_error(e)) from e
275275
return super()._validate_spec(spec)
276276

277277
def __str__(self):

lumen/base.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,7 @@ def _validate_dict_or_list_subtypes(
331331
def _deprecation(
332332
cls, msg: str, key: str, spec: dict[str, Any], update: dict[str, Any]
333333
):
334-
warnings.warn(msg, DeprecationWarning)
334+
warnings.warn(msg, DeprecationWarning, stacklevel=2)
335335
if key not in spec:
336336
spec[key] = {}
337337
spec[key].update(update)
@@ -360,7 +360,7 @@ def _validate_param(cls, key: str, value: Any, spec: dict[str, Any]):
360360
pobj._validate(value)
361361
except Exception as e:
362362
msg = f"{cls.__name__} component {key!r} value failed validation: {e!s}"
363-
raise ValidationError(msg, spec, key)
363+
raise ValidationError(msg, spec, key) from e
364364

365365
@classmethod
366366
def _is_component_key(cls, key: str) -> bool:
@@ -615,7 +615,7 @@ def _import_module(cls, component_type: str):
615615
f"component '{component_type}', the '{e.name}' package "
616616
"must be installed."
617617
)
618-
raise ImportError(msg)
618+
raise ImportError(msg) from e
619619

620620
@classmethod
621621
def _get_type(

0 commit comments

Comments
 (0)