Skip to content

types: align Message.get with __contains__ semantics - #786

Open
AP24110011695 wants to merge 1 commit into
ollama:mainfrom
AP24110011695:fix/message-get-consistency
Open

AP24110011695 wants to merge 1 commit into
ollama:mainfrom
AP24110011695:fix/message-get-consistency

Conversation

@AP24110011695

Copy link
Copy Markdown

Problem

SubscriptableBaseModel.get() used getattr/hasattr, which disagrees with the class's own __contains__ semantics:

  • 'content' in msg is False for a declared-but-unset field (per the existing __contains__ doctests), yet msg.get('content', 'fallback') returned None instead of 'fallback'.
  • Non-field names leak through: msg.get('model_dump') returned the bound method, breaking dict.get expectations.

Fix

Route get through __getitem__/__contains__ so the subscript and .get views agree:

try:
  return self[key]
except KeyError:
  return default

Explicitly-set None values still count as present (like a dict), and the existing __contains__ doctests document that distinction.

Tests

test_message_get_follows_contains_semantics fails on main (35d9667) and passes with this change; a new doctest case documents the fixed behavior. Doctests (pytest --doctest-modules ollama/_types.py) all pass.

get() used getattr/hasattr, so a declared-but-unset field (None default)
was treated as present: 'content' in msg was False while
msg.get('content', 'fallback') returned None instead of 'fallback', and
non-field names leaked through (msg.get('model_dump') returned the bound
method). Route get through __getitem__/__contains__ so the two views
agree, and pin the behavior with a test plus a new doctest case.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant