Skip to content

fix: Resolve UnboundLocalError for first_valid in oneOf validator#1464

Closed
Yuki9814 wants to merge 2 commits intopython-jsonschema:mainfrom
Yuki9814:fix/oneof-unbound-variable
Closed

fix: Resolve UnboundLocalError for first_valid in oneOf validator#1464
Yuki9814 wants to merge 2 commits intopython-jsonschema:mainfrom
Yuki9814:fix/oneof-unbound-variable

Conversation

@Yuki9814
Copy link

Description

Fixes a potential UnboundLocalError in the oneOf validator function.

The Bug

In jsonschema/_keywords.py, the oneOf() function uses a for-else loop to find the first valid schema:

for index, subschema in subschemas:
    errs = list(validator.descend(instance, subschema, schema_path=index))
    if not errs:
        first_valid = subschema
        break
    all_errors.extend(errs)
else:
    yield ValidationError(...)  # No valid schema found

more_valid = [...]
if more_valid:
    more_valid.append(first_valid)  # BUG: first_valid may be unbound!

If the for loop completes without finding a valid schema (the else branch executes), first_valid is never assigned. However, the subsequent if more_valid: block unconditionally tries to append first_valid to the list, which would raise UnboundLocalError: local variable 'first_valid' referenced before assignment.

The Fix

Initialize first_valid = None before the loop and check first_valid is not None before using it:

first_valid = None
for index, subschema in subschemas:
    ...

if more_valid and first_valid is not None:
    more_valid.append(first_valid)
    ...

Testing

All 7,288 existing tests pass with this change.

Yuki9814 and others added 2 commits March 15, 2026 23:45
The first_valid variable was only assigned inside the for-else loop when a valid
schema was found. If no valid schema was found initially but more_valid schemas
were discovered later, the code would attempt to access an undefined variable.

Initialize first_valid to None and check before using it.
@Julian Julian closed this Mar 15, 2026
@Yuki9814 Yuki9814 deleted the fix/oneof-unbound-variable branch March 16, 2026 08:10
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.

2 participants