Skip to content

Commit 3a2eb6e

Browse files
author
Erick Friis
authored
infra: add print rule to ruff (langchain-ai#16221)
Added noqa for existing prints. Can slowly remove / will prevent more being intro'd
1 parent c07c0da commit 3a2eb6e

File tree

246 files changed

+563
-470
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

246 files changed

+563
-470
lines changed

.github/scripts/check_diff.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,4 @@
4747
else:
4848
pass
4949
json_output = json.dumps(list(dirs_to_run))
50-
print(f"dirs-to-run={json_output}")
50+
print(f"dirs-to-run={json_output}") # noqa: T201

.github/scripts/get_min_versions.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,6 @@ def get_min_version_from_toml(toml_path: str):
6262
# Call the function to get the minimum versions
6363
min_versions = get_min_version_from_toml(toml_file)
6464

65-
print(" ".join([f"{lib}=={version}" for lib, version in min_versions.items()]))
65+
print(
66+
" ".join([f"{lib}=={version}" for lib, version in min_versions.items()])
67+
) # noqa: T201

.github/workflows/extract_ignored_words_list.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,4 @@
77
pyproject_toml.get("tool", {}).get("codespell", {}).get("ignore-words-list")
88
)
99

10-
print(f"::set-output name=ignore_words_list::{ignore_words_list}")
10+
print(f"::set-output name=ignore_words_list::{ignore_words_list}") # noqa: T201

docs/api_reference/create_api_rst.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Script for auto-generating api_reference.rst."""
2+
23
import importlib
34
import inspect
45
import os
@@ -186,7 +187,7 @@ def _load_package_modules(
186187
modules_by_namespace[top_namespace] = _module_members
187188

188189
except ImportError as e:
189-
print(f"Error: Unable to import module '{namespace}' with error: {e}")
190+
print(f"Error: Unable to import module '{namespace}' with error: {e}") # noqa: T201
190191

191192
return modules_by_namespace
192193

docs/docs/integrations/document_loaders/example_data/source_code/example.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ def __init__(self, name):
33
self.name = name
44

55
def greet(self):
6-
print(f"Hello, {self.name}!")
6+
print(f"Hello, {self.name}!") # noqa: T201
77

88

99
def main():

docs/scripts/generate_api_reference_links.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def main():
6464
global_imports = {}
6565

6666
for file in find_files(args.docs_dir):
67-
print(f"Adding links for imports in {file}")
67+
print(f"Adding links for imports in {file}") # noqa: T201
6868
file_imports = replace_imports(file)
6969

7070
if file_imports:

libs/cli/langchain_cli/integration_template/pyproject.toml

+1
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ select = [
5858
"E", # pycodestyle
5959
"F", # pyflakes
6060
"I", # isort
61+
"T201", # print
6162
]
6263

6364
[tool.mypy]

libs/cli/langchain_cli/integration_template/scripts/check_imports.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010
SourceFileLoader("x", file).load_module()
1111
except Exception:
1212
has_faillure = True
13-
print(file)
13+
print(file) # noqa: T201
1414
traceback.print_exc()
15-
print()
15+
print() # noqa: T201
1616

1717
sys.exit(1 if has_failure else 0)

libs/cli/pyproject.toml

+1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ select = [
4545
"E", # pycodestyle
4646
"F", # pyflakes
4747
"I", # isort
48+
"T201", # print
4849
]
4950

5051
[tool.poe.tasks]

libs/community/langchain_community/callbacks/arize_callback.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def __init__(
4949
if SPACE_KEY == "SPACE_KEY" or API_KEY == "API_KEY":
5050
raise ValueError("❌ CHANGE SPACE AND API KEYS")
5151
else:
52-
print("✅ Arize client setup done! Now you can start using Arize!")
52+
print("✅ Arize client setup done! Now you can start using Arize!") # noqa: T201
5353

5454
def on_llm_start(
5555
self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any
@@ -161,9 +161,9 @@ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
161161
environment=Environments.PRODUCTION,
162162
)
163163
if response_from_arize.status_code == 200:
164-
print("✅ Successfully logged data to Arize!")
164+
print("✅ Successfully logged data to Arize!") # noqa: T201
165165
else:
166-
print(f'❌ Logging failed "{response_from_arize.text}"')
166+
print(f'❌ Logging failed "{response_from_arize.text}"') # noqa: T201
167167

168168
def on_llm_error(self, error: BaseException, **kwargs: Any) -> None:
169169
"""Do nothing."""

libs/community/langchain_community/callbacks/clearml_callback.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -509,8 +509,8 @@ def flush_tracker(
509509
target_filename=name,
510510
)
511511
except NotImplementedError as e:
512-
print("Could not save model.")
513-
print(repr(e))
512+
print("Could not save model.") # noqa: T201
513+
print(repr(e)) # noqa: T201
514514
pass
515515

516516
# Cleanup after adding everything to ClearML

libs/community/langchain_community/callbacks/confident_callback.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -116,13 +116,13 @@ def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None:
116116
output=output,
117117
query=query,
118118
)
119-
print(f"Answer Relevancy: {result}")
119+
print(f"Answer Relevancy: {result}") # noqa: T201
120120
elif isinstance(metric, UnBiasedMetric):
121121
score = metric.measure(output)
122-
print(f"Bias Score: {score}")
122+
print(f"Bias Score: {score}") # noqa: T201
123123
elif isinstance(metric, NonToxicMetric):
124124
score = metric.measure(output)
125-
print(f"Toxic Score: {score}")
125+
print(f"Toxic Score: {score}") # noqa: T201
126126
else:
127127
raise ValueError(
128128
f"""Metric {metric.__name__} is not supported by deepeval

libs/community/langchain_community/callbacks/infino_callback.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def _send_to_infino(
8686
},
8787
}
8888
if self.verbose:
89-
print(f"Tracking {key} with Infino: {payload}")
89+
print(f"Tracking {key} with Infino: {payload}") # noqa: T201
9090

9191
# Append to Infino time series only if is_ts is True, otherwise
9292
# append to Infino log.
@@ -245,7 +245,7 @@ def on_chat_model_start(
245245
self._send_to_infino("prompt_tokens", prompt_tokens)
246246

247247
if self.verbose:
248-
print(
248+
print( # noqa: T201
249249
f"on_chat_model_start: is_chat_openai_model= \
250250
{self.is_chat_openai_model}, \
251251
chat_openai_model_name={self.chat_openai_model_name}"

libs/community/langchain_community/callbacks/mlflow_callback.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -646,9 +646,11 @@ def on_retriever_end(
646646
{
647647
"page_content": doc.page_content,
648648
"metadata": {
649-
k: str(v)
650-
if not isinstance(v, list)
651-
else ",".join(str(x) for x in v)
649+
k: (
650+
str(v)
651+
if not isinstance(v, list)
652+
else ",".join(str(x) for x in v)
653+
)
652654
for k, v in doc.metadata.items()
653655
},
654656
}
@@ -757,15 +759,15 @@ def flush_tracker(self, langchain_asset: Any = None, finish: bool = False) -> No
757759
langchain_asset.save_agent(langchain_asset_path)
758760
self.mlflg.artifact(langchain_asset_path)
759761
except AttributeError:
760-
print("Could not save model.")
762+
print("Could not save model.") # noqa: T201
761763
traceback.print_exc()
762764
pass
763765
except NotImplementedError:
764-
print("Could not save model.")
766+
print("Could not save model.") # noqa: T201
765767
traceback.print_exc()
766768
pass
767769
except NotImplementedError:
768-
print("Could not save model.")
770+
print("Could not save model.") # noqa: T201
769771
traceback.print_exc()
770772
pass
771773
if finish:

libs/community/langchain_community/callbacks/wandb_callback.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -558,8 +558,8 @@ def flush_tracker(
558558
model_artifact.add_file(str(langchain_asset_path))
559559
model_artifact.metadata = load_json_to_dict(langchain_asset_path)
560560
except NotImplementedError as e:
561-
print("Could not save model.")
562-
print(repr(e))
561+
print("Could not save model.") # noqa: T201
562+
print(repr(e)) # noqa: T201
563563
pass
564564
self.run.log_artifact(model_artifact)
565565

@@ -577,7 +577,9 @@ def flush_tracker(
577577
name=name if name else self.name,
578578
notes=notes if notes else self.notes,
579579
visualize=visualize if visualize else self.visualize,
580-
complexity_metrics=complexity_metrics
581-
if complexity_metrics
582-
else self.complexity_metrics,
580+
complexity_metrics=(
581+
complexity_metrics
582+
if complexity_metrics
583+
else self.complexity_metrics
584+
),
583585
)

libs/community/langchain_community/chat_message_histories/rocksetdb.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ class RocksetChatMessageHistory(BaseChatMessageHistory):
3434
history.add_user_message("hi!")
3535
history.add_ai_message("whats up?")
3636
37-
print(history.messages)
37+
print(history.messages) # noqa: T201
3838
"""
3939

4040
# You should set these values based on your VI.

libs/community/langchain_community/chat_models/deepinfra.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""deepinfra.com chat models wrapper"""
2+
23
from __future__ import annotations
34

45
import json
@@ -207,7 +208,7 @@ def _completion_with_retry(**kwargs: Any) -> Any:
207208
return response
208209
except Exception as e:
209210
# import pdb; pdb.set_trace()
210-
print("EX", e)
211+
print("EX", e) # noqa: T201
211212
raise
212213

213214
return _completion_with_retry(**kwargs)
@@ -231,7 +232,7 @@ async def _completion_with_retry(**kwargs: Any) -> Any:
231232
self._handle_status(response.status, response.text)
232233
return await response.json()
233234
except Exception as e:
234-
print("EX", e)
235+
print("EX", e) # noqa: T201
235236
raise
236237

237238
return await _completion_with_retry(**kwargs)

libs/community/langchain_community/chat_models/human.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""ChatModel wrapper which returns user input as the response.."""
2+
23
from io import StringIO
34
from typing import Any, Callable, Dict, List, Mapping, Optional
45

@@ -30,9 +31,9 @@ def _display_messages(messages: List[BaseMessage]) -> None:
3031
width=10000,
3132
line_break=None,
3233
)
33-
print("\n", "======= start of message =======", "\n\n")
34-
print(yaml_string)
35-
print("======= end of message =======", "\n\n")
34+
print("\n", "======= start of message =======", "\n\n") # noqa: T201
35+
print(yaml_string) # noqa: T201
36+
print("======= end of message =======", "\n\n") # noqa: T201
3637

3738

3839
def _collect_yaml_input(

libs/community/langchain_community/document_loaders/assemblyai.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def load(self) -> List[Document]:
150150
)
151151
transcript_response.raise_for_status()
152152
except Exception as e:
153-
print(f"An error occurred: {e}")
153+
print(f"An error occurred: {e}") # noqa: T201
154154
raise
155155

156156
transcript = transcript_response.json()["text"]
@@ -166,7 +166,7 @@ def load(self) -> List[Document]:
166166
)
167167
paragraphs_response.raise_for_status()
168168
except Exception as e:
169-
print(f"An error occurred: {e}")
169+
print(f"An error occurred: {e}") # noqa: T201
170170
raise
171171

172172
paragraphs = paragraphs_response.json()["paragraphs"]
@@ -181,7 +181,7 @@ def load(self) -> List[Document]:
181181
)
182182
sentences_response.raise_for_status()
183183
except Exception as e:
184-
print(f"An error occurred: {e}")
184+
print(f"An error occurred: {e}") # noqa: T201
185185
raise
186186

187187
sentences = sentences_response.json()["sentences"]
@@ -196,7 +196,7 @@ def load(self) -> List[Document]:
196196
)
197197
srt_response.raise_for_status()
198198
except Exception as e:
199-
print(f"An error occurred: {e}")
199+
print(f"An error occurred: {e}") # noqa: T201
200200
raise
201201

202202
srt = srt_response.text
@@ -211,7 +211,7 @@ def load(self) -> List[Document]:
211211
)
212212
vtt_response.raise_for_status()
213213
except Exception as e:
214-
print(f"An error occurred: {e}")
214+
print(f"An error occurred: {e}") # noqa: T201
215215
raise
216216

217217
vtt = vtt_response.text

libs/community/langchain_community/document_loaders/blackboard.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -109,13 +109,13 @@ def load(self) -> List[Document]:
109109
documents = []
110110
for path in relative_paths:
111111
url = self.base_url + path
112-
print(f"Fetching documents from {url}")
112+
print(f"Fetching documents from {url}") # noqa: T201
113113
soup_info = self._scrape(url)
114114
with contextlib.suppress(ValueError):
115115
documents.extend(self._get_documents(soup_info))
116116
return documents
117117
else:
118-
print(f"Fetching documents from {self.web_path}")
118+
print(f"Fetching documents from {self.web_path}") # noqa: T201
119119
soup_info = self.scrape()
120120
self.folder_path = self._get_folder_path(soup_info)
121121
return self._get_documents(soup_info)
@@ -295,4 +295,4 @@ def _parse_filename_from_url(self, url: str) -> str:
295295
load_all_recursively=True,
296296
)
297297
documents = loader.load()
298-
print(f"Loaded {len(documents)} pages of PDFs from {loader.web_path}")
298+
print(f"Loaded {len(documents)} pages of PDFs from {loader.web_path}") # noqa: T201

libs/community/langchain_community/document_loaders/blob_loaders/file_system.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""Use to load blobs from the local file system."""
2+
23
from pathlib import Path
34
from typing import Callable, Iterable, Iterator, Optional, Sequence, TypeVar, Union
45

@@ -46,7 +47,7 @@ class FileSystemBlobLoader(BlobLoader):
4647
from langchain_community.document_loaders.blob_loaders import FileSystemBlobLoader
4748
loader = FileSystemBlobLoader("/path/to/directory")
4849
for blob in loader.yield_blobs():
49-
print(blob)
50+
print(blob) # noqa: T201
5051
""" # noqa: E501
5152

5253
def __init__(

libs/community/langchain_community/document_loaders/confluence.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -564,7 +564,7 @@ def process_attachment(
564564
texts.append(text)
565565
except requests.HTTPError as e:
566566
if e.response.status_code == 404:
567-
print(f"Attachment not found at {absolute_url}")
567+
print(f"Attachment not found at {absolute_url}") # noqa: T201
568568
continue
569569
else:
570570
raise

libs/community/langchain_community/document_loaders/dropbox.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ def _load_file_from_path(self, file_path: str) -> Optional[Document]:
121121
file_extension = os.path.splitext(file_path)[1].lower()
122122

123123
if file_extension == ".pdf":
124-
print(f"File {file_path} type detected as .pdf")
124+
print(f"File {file_path} type detected as .pdf") # noqa: T201
125125
from langchain_community.document_loaders import UnstructuredPDFLoader
126126

127127
# Download it to a temporary file.
@@ -136,10 +136,10 @@ def _load_file_from_path(self, file_path: str) -> Optional[Document]:
136136
if docs:
137137
return docs[0]
138138
except Exception as pdf_ex:
139-
print(f"Error while trying to parse PDF {file_path}: {pdf_ex}")
139+
print(f"Error while trying to parse PDF {file_path}: {pdf_ex}") # noqa: T201
140140
return None
141141
else:
142-
print(
142+
print( # noqa: T201
143143
f"File {file_path} could not be decoded as pdf or text. Skipping."
144144
)
145145

0 commit comments

Comments
 (0)