Warn when a string is passed as choices to OneOf - #3027
Open
ChrisJr404 wants to merge 1 commit into
Open
Conversation
A string is a valid iterable, so validate.OneOf("one", "two") silently
treats "one" as the choices and "two" as the labels, and each character
becomes a separate choice. Emit a warning to flag this likely mistake;
wrapping the string in a list silences it. ContainsOnly deliberately
accepts strings, so only plain OneOf instances warn.
Closes marshmallow-code#2074
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #2074.
A string is a valid iterable, so it "works" as
choicesforOneOf— but it's almost always a mistake. The motivating case from the issue:"one" in "one"isTrue, so the value"one"validates, and each character of the string is treated as a separate choice in the error text and in.options(). This is easy to hit and hard to spot.This PR emits a
UserWarning(atstacklevel=2, so it points at the caller) when a plainOneOfis constructed with astrforchoices. Wrapping the string in a list silences it, as @deckar01 suggested on the issue:ContainsOnlysubclassesOneOfbut legitimately accepts a string as a character set (that usage is covered by the existing test suite), so the warning is scoped to exactOneOfinstances viatype(self) is OneOfandContainsOnlyis unaffected. Behaviour is otherwise unchanged — string choices still validate exactly as before.test_oneof_string_choices_warnscovering the warning, the list-wrapping silence path, and thatContainsOnlydoes not warn.test_oneofto expect the warning.AUTHORS.rstline.