question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Validate field based on other optional fields

See original GitHub issue

Question

  • OS: macOS Mojave
  • Python version: 3.7.0
  • Pydantic version: 0.21

I’m currently working with pydantic in a scenario where I’d like to validate an instantiation of MyClass to ensure that certain optional fields are set or not set depending on the value of an enum. However, I’m noticing in the @validator('my_field'), only required fields are present in values regardless if they’re actually populated with values.

import enum
from pydantic import BaseModel, validator

class MyEnum(enum.Enum):
    ENUM_VALUE = 'foo'
    OTHER_VALUE = 'bar'


class MyClass(BaseModel):
    required_float: float
    my_enum: MyEnum
    optional_float: float = 0.0

    @validator('my_enum')
    def ensure_stuff_exists(cls, v, values, **kwargs):
        if v == MyEnum.ENUM_VALUE and values['optional_float'] is not None:
            raise KeyError('foo')


MyClass(
    my_enum=MyEnum.ENUM_VALUE,
    required_float=4.0,
    optional_float=22.0,
)
...

In the above example, only required_float and my_enum would be populated in values, I am unable to inspect the value of optional_float, even though it is populated with a value upon instantiation. Is there any way to perform this type of validation? I hope this example makes sense.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:11 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
samuelcolvincommented, Apr 20, 2019

Yes, fields are populated in the order they’re defined in the class, so just move my_enum down one line to below optional_float.

1reaction
SethMMortoncommented, Aug 3, 2019

Digging deeper, this comment first appeared in https://github.com/samuelcolvin/pydantic/commit/5efa54d80d8a584e4c369e2ccdf30d723e54db3b, with the note “switch annotation only fields to come first in fields list not last”. It seems like they have always been separated, but before they were after optional, not before.

Based on some of the diffs I saw in that commit, I got an idea to make all my required fields non-annotation-only by adding ....

class ExampleWithOptional(pydantic.BaseModel):
    foo: List[int] = [1, 2]
    bar: int = ...

    @pydantic.validator("bar")
    def add_length_of_foo_to_bar(cls, value, values, **kwargs):
        return value + len(values["foo"])

This got it to work as well.


So, there is a workaround! If it is not possible to get what I was originally trying to do to work, it might be nice to add to the docs that you can make it work with = ....

Read more comments on GitHub >

github_iconTop Results From Across the Web

Validate field based on other optional fields #483 - GitHub
This makes it challenging to validate required fields based on the values of optional fields.
Read more >
Required Field Validation Based on Another Column's Value ...
Here is how to implement a required field validation based on other column values in SharePoint 2013. Head on the List Settings; Click...
Read more >
Form Validation for Optional Fields - Stack Overflow
What I'm trying to do is make it so if a text field does not contain the "required" class and the field is...
Read more >
forms - Validation for if all fields are required when an optional ...
Only show those fields when they are required to be used. This way if the user only wants to specify the domain name,...
Read more >
Validate a field based on the value of another field - jQWidgets
I need to validate a field based on the value of another field. ... <label for=”other”>Check to make next field required</label>
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found