marshmallow-code / marshmallow-code/marshmallow

[validate.oneOf] Returning labels?

Open
#1,895 1 comment 0 reactions 0 assignees View on GitHub
backwards incompat
Dominant language
Python
Stars
7.2k
Forks
738
Avg merge
1d 23h
Merged PRs (30d)
7

Description

Hello guys,

Few days ago I was trying to validate a field using something similar to this:
```python
foo = fields.Str(validate=validate.OneOf(choices=[1, 2, 3], labels=["one", "two", "three"))
```

The input should be one of the choice integers, but I wish that my return object had the string label instead. Like this:
```python
>>> from marshmallow.validate import OneOf
>>> foo = OneOf(choices=[1, 2, 3], labels=["one", "two", "three"])
>>> foo(1)
'one'
```

I managed to do it by working around with `@post_load`, but I didnt liked it, so I was thinking about...

- What is the real use for the `labels` on the `oneOf` validator?

In my research, i found out that labels are only used in the method `OneOf.options()`, wich only returns a generator object that barely can be used in my example.
If we use different lengths for choices and labels, the `OneOf.options()` is kind of useless / crazy.

IMHO, I think that would be awesome to:
- "automatically" return the labels if there is one
- validate the choices and labels length, for consistency

I actually can do the code, tests and the PR, but want to validate the idea before.

What do you guys think about?

Contributor guide

Open the contributing guide

Research direction

Review marshmallow.validate.OneOf and its options() method, along with the proposed @post_load workaround. Clarify whether labels should transform returned values and how mismatched choices and labels should behave; implementation and tests are not defined until that design is accepted.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.