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.

[Questions] Support empty string with int, date validation

See original GitHub issue

Hi!

Is pydantic support empty values? I didn’t see anything in docs about empty or blank values. I have seen that I could write custom validator and return None when string is empty but maybe there is easier solution. Or if there is option to support empty values in future?

from datetime import date
from typing import Optional
from pydantic import BaseModel

class CustomModel(BaseModel):
    custom_int: Optional[int] = None 
    custom_date: Optional[date] = None

CustomModel(**{'custom_int': '', 'custom_date': ''})
ValidationError: 4 validation errors
custom_int
  value is not a valid integer (type=type_error.integer)
custom_int
  value is not none (type=type_error.none.allowed)
custom_date
  invalid date format (type=type_error.date)
custom_date
  value is not none (type=type_error.none.allowed)

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

4reactions
tiangolocommented, Jan 20, 2019

Just as a note or “workaround” @krzysieqq:

Although it is not really “empty string values accepted as date”, you can define a field as a Union of other types (“union” means “any of these types”). And you can then use Pydantic’s constr() to create a type str with constraints, making it only accept empty strings.

So, this code:

import json
from datetime import date
from typing import Optional, Union
from pydantic import BaseModel, constr

class CustomModel(BaseModel):
    custom_int: Optional[Union[int, constr(max_length=0)]] = None 
    custom_date: Optional[Union[date, constr(max_length=0)]] = None

print(CustomModel(**{'custom_int': '', 'custom_date': ''}).json())

print(CustomModel(**{'custom_int': 3, 'custom_date': '2019-01-20'}).json())

print(CustomModel(**{'custom_int': 'str but not empty', 'custom_date': 'str but not empty'}).json())

would print:

{"custom_int": "", "custom_date": ""}
{"custom_int": 3, "custom_date": "2019-01-20"}
Traceback (most recent call last):
  File "sand.py", line 14, in <module>
    print(CustomModel(**{'custom_int': 'str but not empty', 'custom_date': 'str but not empty'}).json())
  File "/home/user/code/pydantic/pydantic/main.py", line 142, in __init__
    self.__setstate__(self._process_values(data))
  File "/home/user/code/pydantic/pydantic/main.py", line 312, in _process_values
    return validate_model(self, input_data)
  File "/home/user/code/pydantic/pydantic/main.py", line 474, in validate_model
    raise ValidationError(errors)
pydantic.error_wrappers.ValidationError: 6 validation errors
custom_int
  value is not a valid integer (type=type_error.integer)
custom_int
  ensure this value has at most 0 characters (type=value_error.any_str.max_length; limit_value=0)
custom_int
  value is not none (type=type_error.none.allowed)
custom_date
  invalid date format (type=type_error.date)
custom_date
  ensure this value has at most 0 characters (type=value_error.any_str.max_length; limit_value=0)
custom_date
  value is not none (type=type_error.none.allowed)

Note that the first two lines (with “valid data” for your use case) are taken as valid.

So, an empty string is actually accepted. And it shows an error only when the value passed is not of the first type (int, date) or is a non-empty string.

1reaction
krzysieqqcommented, Jan 21, 2019

Thx for help and workaround 😃!

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to allow the empty string when validating an integer value
Use modulus by 1, to allow empty string when validating integers: var isNum = inputString % 1 === 0;. As said in the...
Read more >
Assign empty string '' if datetime is null - TechNet - Microsoft
hi all,. may i know how to assign '' (empty string) for a varible is null which type is datetime? example: select EnterTime...
Read more >
getting Transformation Error while converting empty string to ...
I have a Expression Transformation that converts input string to a date. Input is of format MM/DD/YYYY (from SQLServer source table). Input data...
Read more >
Data conversion parameters - Amazon Redshift
Empty fields for other data types, such as INT, are always loaded with NULL. Empty fields occur when data contains two delimiters in...
Read more >
Empty strings as None (revisited) · Issue #713 - GitHub
I'd like to revisit this suggestion - allowing empty strings to be interpreted as None: #543 I understand the sentiment of the response: ......
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