Skip to content

Raise the document_class error message for non-class values - #3260

Open
qianeric-backup wants to merge 1 commit into
mongodb:mainfrom
qianeric-backup:fix/document-class-typeerror
Open

qianeric-backup wants to merge 1 commit into
mongodb:mainfrom
qianeric-backup:fix/document-class-typeerror

Conversation

@qianeric-backup

Copy link
Copy Markdown

validate_document_class() has a TypeError guard for exactly this case, and then calls issubclass() a second time outside it:

    check_class = getattr(value, "__origin__", value)
    try:
        is_mapping = issubclass(check_class, abc.MutableMapping)
    except TypeError:
        is_mapping = False
    if not is_mapping and not issubclass(value, RawBSONDocument):
        raise TypeError(
            f"{option} must be dict, bson.son.SON, "
            "bson.raw_bson.RawBSONDocument, or a "
            "subclass of collections.MutableMapping"
        )

The second call is only reached when is_mapping is false, which is precisely when value is not a class — so it raises from <frozen abc> before the descriptive TypeError two lines below can run, and that message is unreachable for the inputs it was written for:

>>> from pymongo.common import validate_document_class
>>> validate_document_class("document_class", 42)
Traceback (most recent call last):
  File ".../pymongo/common.py", line 550, in validate_document_class
    if not is_mapping and not issubclass(value, RawBSONDocument):
TypeError: issubclass() arg 1 must be a class

Same for an instance instead of a class, a string, or list[int]:

>>> validate_document_class("document_class", RawBSONDocument.__new__(RawBSONDocument))
TypeError: issubclass() arg 1 must be a class
>>> validate_document_class("document_class", "dict")
TypeError: issubclass() arg 1 must be a class
>>> validate_document_class("document_class", list[int])
TypeError: issubclass() arg 1 must be a class

The traceback points at abc rather than at the option, so anyone passing document_class="SON" in a config file gets no indication of which setting is wrong or what the accepted values are. The comment above the first check — "issubclass() raises TypeError for such aliases, so check the origin proactively instead of relying on catching the error" — is describing this hazard, and the second call defeats it.

Fix

Fold both issubclass() calls into the guarded try, so a non-class value takes the same path as a generic alias:

    check_class = getattr(value, "__origin__", value)
    try:
        is_mapping = issubclass(check_class, abc.MutableMapping) or issubclass(
            value, RawBSONDocument
        )
    except TypeError:
        # `value` is not a class at all (for example an instance was passed
        # instead of a class), so neither issubclass() call is meaningful.
        is_mapping = False
    if not is_mapping:
        raise TypeError(...)

Note or rather than and: RawBSONDocument subclasses are not MutableMapping, so the second check still has to be able to make the call succeed on its own. Short-circuiting means the issubclass(value, ...) arm only runs when the first is False, i.e. exactly in the cases where the guard matters.

After the change:

>>> validate_document_class("document_class", 42)
TypeError: document_class must be dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a subclass of collections.MutableMapping

Tests

New test/test_common_validation.py (pure unittest, no server needed) covering the validator directly: accepted values (dict, SON, RawBSONDocument, a RawBSONDocument subclass, and the generic aliases dict[str, Any] / SON[str, Any] that the existing __origin__ handling exists for), and rejected values (42, "dict", list[int], an instance) asserting the descriptive message.

  • Red, on current main with only the test file added: 9 failed, 3 passed (the rejected-value cases get issubclass() arg 1 must be a class)
  • Green, with the change: 4 passed, 19 subtests passed
  • Whole suite, module by module (no mongod here): 121 modules before, 122 after; comm -3 of the failing sets between main and the patched tree is empty. The 10 pre-existing failures are identical on both trees and are environment-only: test_kms_connect ×4 (no pymongocrypt), test_ocsp_support ×3 (no OCSP responder), test_sfp ×3 (no SFP_ATLAS_X509_URI).
  • The 15-value matrix (dict, SON, RawBSONDocument, a subclass, an instance, 42, "dict", list[int], dict[str, int], …) shows only the four illegal inputs changing exception, and the seven legal inputs returning byte-identical values.
  • ruff==0.17.3 (the [dependency-groups] lint pin): ruff check . and ruff format --check . (466 files) clean on both trees.

Ticket

CONTRIBUTING.md asks for a PYTHON- ticket up front. I searched JIRA and there isn't one for this (validate_document_class hits only PYTHON-4192, which is a different, blocked feature); creating one needs a JIRA account I don't have. Happy to rename the branch and commit, and to add the ticket reference to the changelog, as soon as a number exists — or to close this if you'd rather have it filed first.

AI disclosure

Written with an AI coding assistant (Claude), which located the unreachable branch and ran the before/after comparison. The change and the test expectations were reviewed by hand against unpatched main.

validate_document_class guards the first issubclass() call against
TypeError and then makes a second issubclass(value, RawBSONDocument)
call outside that guard. The second call is only reached when value is
not a mapping, which includes not being a class at all, so it raises
"issubclass() arg 1 must be a class" from abc and the descriptive
TypeError below it is unreachable.

Fold both checks into the guarded try so a non-class value reports the
option name and the accepted values instead.
@qianeric-backup
qianeric-backup marked this pull request as ready for review November 27, 2026 08:04
@qianeric-backup
qianeric-backup requested a review from a team as a code owner November 27, 2026 08:04

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