Skip to content

Commit

Permalink
chore(weave): ruff: enable TRY004 (#2903)
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewtruong authored Nov 6, 2024
1 parent 5332bf5 commit 564f61d
Show file tree
Hide file tree
Showing 22 changed files with 46 additions and 45 deletions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ select = [
"TID252", # https://docs.astral.sh/ruff/rules/relative-imports/#relative-imports-tid252
"UP", # https://docs.astral.sh/ruff/rules/#pyupgrade-up
"TRY002", # https://docs.astral.sh/ruff/rules/raise-vanilla-class/
"TRY004", # https://docs.astral.sh/ruff/rules/type-check-without-type-error/
"C", # https://docs.astral.sh/ruff/rules/#convention-c
]
ignore = [
Expand Down
8 changes: 4 additions & 4 deletions tests/trace/test_weave_client_mutations.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,16 +312,16 @@ def test_table_mutation_saving_replace_rows(client):

def test_table_cant_append_bad_data(client):
t = weave.Table(rows=[{"a": 1, "b": 2}])
with pytest.raises(ValueError):
with pytest.raises(TypeError):
t.append(1)
with pytest.raises(ValueError):
with pytest.raises(TypeError):
t.append([1, 2, 3])

ref = weave.publish(t)
t2 = ref.get()
with pytest.raises(ValueError):
with pytest.raises(TypeError):
t2.append(1)
with pytest.raises(ValueError):
with pytest.raises(TypeError):
t2.append([1, 2, 3])


Expand Down
4 changes: 2 additions & 2 deletions weave/deploy/gcp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ def deploy(
dir = compile(model_ref, model_method, wandb_project, auth_entity, base_image)
ref = parse_uri(model_ref)
if not isinstance(ref, ObjectRef):
raise ValueError(f"Expected a weave object uri, got {type(ref)}")
raise TypeError(f"Expected a weave object uri, got {type(ref)}")
name = safe_name(f"{ref.project}-{ref.name}")
project = wandb_project or ref.project
key = env.weave_wandb_api_key()
Expand Down Expand Up @@ -310,7 +310,7 @@ def develop(
)
model_uri = parse_uri(model_ref)
if not isinstance(model_uri, ObjectRef):
raise ValueError(f"Expected a weave object uri, got {type(model_uri)}")
raise TypeError(f"Expected a weave object uri, got {type(model_uri)}")
name = safe_name(model_uri.name)
docker = shutil.which("docker")
if docker is None:
Expand Down
2 changes: 1 addition & 1 deletion weave/deploy/modal/stub.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def fastapi_app() -> FastAPI:

uri_ref = parse_uri(os.environ["MODEL_REF"])
if not isinstance(uri_ref, ObjectRef):
raise ValueError(f"Expected a weave object uri, got {type(uri_ref)}")
raise TypeError(f"Expected a weave object uri, got {type(uri_ref)}")
app = object_method_app(uri_ref, auth_entity=os.environ.get("AUTH_ENTITY"))

api.init(os.environ["PROJECT_NAME"])
Expand Down
2 changes: 1 addition & 1 deletion weave/flow/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def convert_to_table(cls, rows: Any) -> weave.Table:
raise ValueError("Attempted to construct a Dataset with an empty list.")
for row in rows.rows:
if not isinstance(row, dict):
raise ValueError(
raise TypeError(
"Attempted to construct a Dataset with a non-dict object. Found type: "
+ str(type(row))
+ " of row: "
Expand Down
2 changes: 1 addition & 1 deletion weave/flow/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def model_post_init(self, __context: Any) -> None:
if isinstance(scorer, Scorer):
pass
elif isinstance(scorer, type):
raise ValueError(
raise TypeError(
f"Scorer {scorer.__name__} must be an instance, not a class. Did you forget to instantiate?"
)
elif callable(scorer) and not is_op(scorer):
Expand Down
4 changes: 2 additions & 2 deletions weave/flow/prompt/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def append(
for item in item:
self.append(item)
else:
raise ValueError(f"Cannot append {item} of type {type(item)} to Prompt")
raise TypeError(f"Cannot append {item} of type {type(item)} to Prompt")

def __iadd__(self, item: Any) -> "Prompt":
self.append(item)
Expand Down Expand Up @@ -401,7 +401,7 @@ def from_obj(obj: Any) -> "EasyPrompt":
@staticmethod
def load(fp: IO) -> "EasyPrompt":
if isinstance(fp, str): # Common mistake
raise ValueError(
raise TypeError(
"Prompt.load() takes a file-like object, not a string. Did you mean Prompt.e()?"
)
data = json.load(fp)
Expand Down
2 changes: 1 addition & 1 deletion weave/scorers/moderation_scorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def validate_openai_client(cls, v: _LLM_CLIENTS) -> _LLM_CLIENTS:
raise ValueError("Install openai to use this scorer")

if not isinstance(v, (OpenAI, AsyncOpenAI)):
raise ValueError("Moderation scoring only works with OpenAI or AsyncOpenAI")
raise TypeError("Moderation scoring only works with OpenAI or AsyncOpenAI")
return v

@weave.op
Expand Down
2 changes: 1 addition & 1 deletion weave/scorers/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ def stringify(output: Any) -> str:
elif isinstance(output, BaseModel):
return output.model_dump_json(indent=2)
else:
raise ValueError(f"Unsupported model output type: {type(output)}")
raise TypeError(f"Unsupported model output type: {type(output)}")
2 changes: 1 addition & 1 deletion weave/trace/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def ref(location: str) -> weave_client.ObjectRef:

uri = parse_uri(location)
if not isinstance(uri, weave_client.ObjectRef):
raise ValueError("Expected an object ref")
raise TypeError("Expected an object ref")
return uri


Expand Down
2 changes: 1 addition & 1 deletion weave/trace/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def serve(
) -> None:
parsed_ref = parse_uri(model_ref)
if not isinstance(parsed_ref, ObjectRef):
raise ValueError(f"Expected a weave artifact uri, got {parsed_ref}")
raise TypeError(f"Expected a weave artifact uri, got {parsed_ref}")
ref_project = parsed_ref.project
project_override = project or os.getenv("PROJECT_NAME")
if project_override:
Expand Down
2 changes: 1 addition & 1 deletion weave/trace/object_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def pydantic_model_fields(obj: PydanticBaseModelGeneral) -> list[str]:
elif isinstance(obj, pydantic.v1.BaseModel):
return obj.__fields__
else:
raise ValueError(f"{obj} is not a pydantic model")
raise TypeError(f"{obj} is not a pydantic model")


def pydantic_asdict_one_level(obj: PydanticBaseModelGeneral) -> dict[str, Any]:
Expand Down
2 changes: 1 addition & 1 deletion weave/trace/refs.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,5 +279,5 @@ def parse_uri(uri: str) -> AnyRef:

def parse_op_uri(uri: str) -> OpRef:
if not isinstance(parsed := parse_uri(uri), OpRef):
raise ValueError(f"URI is not for an Op: {uri}")
raise TypeError(f"URI is not for an Op: {uri}")
return parsed
2 changes: 1 addition & 1 deletion weave/trace/serve_fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def object_method_app(
f"Type for model's method '{method_name}' could not be determined. Did you annotate it with Python types? {e}"
)
if not isinstance(args, op_args.OpNamedArgs):
raise ValueError("predict op must have named args")
raise TypeError("predict op must have named args")

arg_types = args.weave_type().property_types
del arg_types["self"]
Expand Down
2 changes: 1 addition & 1 deletion weave/trace/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def __eq__(self, other: Any) -> bool:
def append(self, row: dict) -> None:
"""Add a row to the table."""
if not isinstance(row, dict):
raise ValueError("Can only append dicts to tables")
raise TypeError("Can only append dicts to tables")
self.rows.append(row)

def pop(self, index: int) -> None:
Expand Down
8 changes: 4 additions & 4 deletions weave/trace/vals.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def add_mutation(

def save(self) -> ObjectRef:
if not isinstance(self.ref, ObjectRef):
raise ValueError("Can only save from object refs")
raise TypeError("Can only save from object refs")
if self.root is not self:
raise ValueError("Can only save from root object")
if self.mutations is None:
Expand Down Expand Up @@ -444,7 +444,7 @@ def __iter__(self) -> Iterator[dict]:

def append(self, val: dict) -> None:
if not isinstance(val, dict):
raise ValueError("Can only append dicts to tables")
raise TypeError("Can only append dicts to tables")
self._mark_dirty()
self.rows.append(val)

Expand Down Expand Up @@ -483,15 +483,15 @@ def __deepcopy__(self, memo: dict) -> "WeaveList":

def __getitem__(self, i: Union[SupportsIndex, slice]) -> Any:
if isinstance(i, slice):
raise ValueError("Slices not yet supported")
raise TypeError("Slices not yet supported")
index = operator.index(i)
new_ref = self.ref.with_index(index) if self.ref else None
index_val = super().__getitem__(index)
return make_trace_obj(index_val, new_ref, self.server, self.root)

def __setitem__(self, i: Union[SupportsIndex, slice], value: Any) -> None:
if isinstance(i, slice):
raise ValueError("Slices not yet supported")
raise TypeError("Slices not yet supported")
if (index := operator.index(i)) >= len(self):
raise IndexError("list assignment index out of range")

Expand Down
12 changes: 6 additions & 6 deletions weave/trace/weave_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def get_obj_name(val: Any) -> str:
else:
name = f"{val.__class__.__name__}"
if not isinstance(name, str):
raise ValueError(f"Object's name attribute is not a string: {name}")
raise TypeError(f"Object's name attribute is not a string: {name}")
return name


Expand Down Expand Up @@ -561,7 +561,7 @@ def save(self, val: Any, name: str, branch: str = "latest") -> Any:

ref = self._save_object(val, name, branch)
if not isinstance(ref, ObjectRef):
raise ValueError(f"Expected ObjectRef, got {ref}")
raise TypeError(f"Expected ObjectRef, got {ref}")
return self.get(ref)

@trace_sentry.global_trace_sentry.watch()
Expand Down Expand Up @@ -1122,7 +1122,7 @@ def send_score_call() -> str:
scorer_op_ref_uri = score_call.op_name
scorer_op_ref = parse_uri(scorer_op_ref_uri)
if not isinstance(scorer_op_ref, OpRef):
raise ValueError(f"Invalid scorer op ref: {scorer_op_ref_uri}")
raise TypeError(f"Invalid scorer op ref: {scorer_op_ref_uri}")
score_name = scorer_op_ref.name
score_results = score_call.output

Expand Down Expand Up @@ -1155,13 +1155,13 @@ def _add_score(
# Parse the refs (acts as validation)
call_ref = parse_uri(call_ref_uri)
if not isinstance(call_ref, CallRef):
raise ValueError(f"Invalid call ref: {call_ref_uri}")
raise TypeError(f"Invalid call ref: {call_ref_uri}")
scorer_call_ref = parse_uri(scorer_call_ref_uri)
if not isinstance(scorer_call_ref, CallRef):
raise ValueError(f"Invalid scorer call ref: {scorer_call_ref_uri}")
raise TypeError(f"Invalid scorer call ref: {scorer_call_ref_uri}")
scorer_op_ref = parse_uri(scorer_op_ref_uri)
if not isinstance(scorer_op_ref, OpRef):
raise ValueError(f"Invalid scorer op ref: {scorer_op_ref_uri}")
raise TypeError(f"Invalid scorer op ref: {scorer_op_ref_uri}")

# Validate score_name (we might want to relax this in the future)
if score_name != scorer_op_ref.name:
Expand Down
4 changes: 2 additions & 2 deletions weave/trace_server/calls_query_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -757,7 +757,7 @@ def process_operation(operation: tsi_query.Operation) -> str:
position_operation = "positionCaseInsensitive"
cond = f"{position_operation}({lhs_part}, {rhs_part}) > 0"
else:
raise ValueError(f"Unknown operation type: {operation}")
raise TypeError(f"Unknown operation type: {operation}")

return cond

Expand Down Expand Up @@ -790,7 +790,7 @@ def process_operand(operand: "tsi_query.Operand") -> str:
):
return process_operation(operand)
else:
raise ValueError(f"Unknown operand type: {operand}")
raise TypeError(f"Unknown operand type: {operand}")

filter_cond = process_operation(query.expr_)

Expand Down
10 changes: 5 additions & 5 deletions weave/trace_server/clickhouse_trace_server_batched.py
Original file line number Diff line number Diff line change
Expand Up @@ -668,7 +668,7 @@ def table_create(self, req: tsi.TableCreateReq) -> tsi.TableCreateRes:
insert_rows = []
for r in req.table.rows:
if not isinstance(r, dict):
raise ValueError(
raise TypeError(
f"""Validation Error: Encountered a non-dictionary row when creating a table. Please ensure that all rows are dictionaries. Violating row:\n{r}."""
)
row_json = json.dumps(r)
Expand Down Expand Up @@ -732,7 +732,7 @@ def table_update(self, req: tsi.TableUpdateReq) -> tsi.TableUpdateRes:

def add_new_row_needed_to_insert(row_data: Any) -> str:
if not isinstance(row_data, dict):
raise ValueError("All rows must be dictionaries")
raise TypeError("All rows must be dictionaries")
row_json = json.dumps(row_data)
row_digest = str_digest(row_json)
if row_digest not in known_digests:
Expand Down Expand Up @@ -768,7 +768,7 @@ def add_new_row_needed_to_insert(row_data: Any) -> str:
final_row_digests.insert(update.insert.index, new_digest)
updated_digests.append(new_digest)
else:
raise ValueError("Unrecognized update", update)
raise TypeError("Unrecognized update", update)

if new_rows_needed_to_insert:
self._insert(
Expand Down Expand Up @@ -1840,7 +1840,7 @@ def _dict_value_to_dump(
value: dict,
) -> str:
if not isinstance(value, dict):
raise ValueError(f"Value is not a dict: {value}")
raise TypeError(f"Value is not a dict: {value}")
return json.dumps(value)


Expand All @@ -1853,7 +1853,7 @@ def _any_value_to_dump(
def _dict_dump_to_dict(val: str) -> dict[str, Any]:
res = json.loads(val)
if not isinstance(res, dict):
raise ValueError(f"Value is not a dict: {val}")
raise TypeError(f"Value is not a dict: {val}")
return res


Expand Down
4 changes: 2 additions & 2 deletions weave/trace_server/orm.py
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ def process_operation(operation: tsi_query.Operation) -> str:
position_operation = "positionCaseInsensitive"
cond = f"{position_operation}({lhs_part}, {rhs_part}) > 0"
else:
raise ValueError(f"Unknown operation type: {operation}")
raise TypeError(f"Unknown operation type: {operation}")

return cond

Expand Down Expand Up @@ -686,7 +686,7 @@ def process_operand(operand: tsi_query.Operand) -> str:
):
return process_operation(operand)
else:
raise ValueError(f"Unknown operand type: {operand}")
raise TypeError(f"Unknown operand type: {operand}")

filter_cond = process_operation(query.expr_)

Expand Down
10 changes: 5 additions & 5 deletions weave/trace_server/sqlite_trace_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ def process_operation(operation: tsi_query.Operation) -> str:
rhs_part = f"LOWER({rhs_part})"
cond = f"instr({lhs_part}, {rhs_part})"
else:
raise ValueError(f"Unknown operation type: {operation}")
raise TypeError(f"Unknown operation type: {operation}")

return cond

Expand Down Expand Up @@ -380,7 +380,7 @@ def process_operand(operand: tsi_query.Operand) -> str:
):
return process_operation(operand)
else:
raise ValueError(f"Unknown operand type: {operand}")
raise TypeError(f"Unknown operand type: {operand}")

filter_cond = process_operation(req.query.expr_)

Expand Down Expand Up @@ -722,7 +722,7 @@ def table_create(self, req: tsi.TableCreateReq) -> tsi.TableCreateRes:
insert_rows = []
for r in req.table.rows:
if not isinstance(r, dict):
raise ValueError("All rows must be dictionaries")
raise TypeError("All rows must be dictionaries")
row_json = json.dumps(r)
row_digest = str_digest(row_json)
insert_rows.append((req.table.project_id, row_digest, row_json))
Expand Down Expand Up @@ -770,7 +770,7 @@ def table_update(self, req: tsi.TableUpdateReq) -> tsi.TableUpdateRes:

def add_new_row_needed_to_insert(row_data: Any) -> str:
if not isinstance(row_data, dict):
raise ValueError("All rows must be dictionaries")
raise TypeError("All rows must be dictionaries")
row_json = json.dumps(row_data)
row_digest = str_digest(row_json)
if row_digest not in known_digests:
Expand Down Expand Up @@ -799,7 +799,7 @@ def add_new_row_needed_to_insert(row_data: Any) -> str:
final_row_digests.insert(update.insert.index, new_digest)
updated_digests.append(new_digest)
else:
raise ValueError("Unrecognized update", update)
raise TypeError("Unrecognized update", update)

# Perform the actual DB inserts
with self.lock:
Expand Down
4 changes: 2 additions & 2 deletions weave/trace_server/trace_server_interface_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def encode_bytes_as_b64(contents: dict[str, bytes]) -> dict[str, str]:
if isinstance(v, bytes):
res[k] = base64.b64encode(v).decode("ascii")
else:
raise ValueError(f"Unexpected type for file {k}: {type(v)}")
raise TypeError(f"Unexpected type for file {k}: {type(v)}")
return res


Expand All @@ -44,7 +44,7 @@ def decode_b64_to_bytes(contents: dict[str, str]) -> dict[str, bytes]:
if isinstance(v, str):
res[k] = base64.b64decode(v.encode("ascii"))
else:
raise ValueError(f"Unexpected type for file {k}: {type(v)}")
raise TypeError(f"Unexpected type for file {k}: {type(v)}")
return res


Expand Down

0 comments on commit 564f61d

Please sign in to comment.