Skip to content

fix: unchecked key lookup in Python dict #4517

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions chromadb/api/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,14 @@ def to_json(self) -> Dict[str, Any]:
def from_json(cls, json_map: Dict[str, Any]) -> Self:
"""Returns a configuration from the given JSON string."""
if cls.__name__ != json_map.get("_type", None):
raise ValueError(
f"Trying to instantiate configuration of type {cls.__name__} from JSON with type {json_map['_type']}"
)
if '_type' in json_map:
raise ValueError(
f"Trying to instantiate configuration of type {cls.__name__} from JSON with type {json_map.get('_type')}"
Comment on lines +209 to +210
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[BestPractice]

The error message improvement is good, but there's a potential inefficiency in accessing json_map.get('_type') twice. Since you're already checking if '_type' is in json_map, you can access it directly in the error message instead of using get again.

Suggested change
raise ValueError(
f"Trying to instantiate configuration of type {cls.__name__} from JSON with type {json_map.get('_type')}"
raise ValueError(
f"Trying to instantiate configuration of type {cls.__name__} from JSON with type {json_map['_type']}"
)

Committable suggestion

Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue is that json_map might not have '_type'.

)
else:
raise ValueError(
f"Trying to instantiate configuration of type {cls.__name__} from JSON, but no type found in json_map"
)
parameters = []
for name, value in json_map.items():
# Type value is only for storage
Expand Down