Skip to content

Commit

Permalink
fix(validators): Stop converting default when is_type_of is set to str (
Browse files Browse the repository at this point in the history
#1066)

* fix(validators): Stop converting default when is_type_of is set to str

When a validator defines both `is_type_of=str, default="0.30"` the
validation process SHOULD NOT convert the default to a float, so
the current solution was to bypass toml by adding extra quotes.

NOTE: Future solution, in 4.0.0 will be to decouple defaults declaration
from validation declaration, and completely remove the tomlfy function

fix: #1064
  • Loading branch information
rochacbruno committed Mar 22, 2024
1 parent 7bf799c commit b528e92
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 6 deletions.
10 changes: 4 additions & 6 deletions dynaconf/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,12 +257,10 @@ def _validate_items(
# to default on validator (see #585)
# The solution we added on #667 introduced a new problem
# This fix here makes it to work for both cases.
if (
isinstance(default_value, str)
and default_value.startswith(("+", "-"))
and self.is_type_of is str
):
# avoid TOML from parsing "+-1" as integer
# This guard also fixes #1064 assuming that any validator
# having is_type_of=str wants to bypass toml inference.
if isinstance(default_value, str) and self.is_type_of is str:
# avoid TOML from parsing "+-1" started strings as integer
default_value = f"'{default_value}'"

value = settings.setdefault(
Expand Down
28 changes: 28 additions & 0 deletions tests_functional/issues/1064_validator_default_type/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from __future__ import annotations

from dynaconf import Dynaconf
from dynaconf import Validator

# Load config files
config = Dynaconf(settings_files=["settings.toml"])


validators = [
Validator(
"version",
is_type_of=str,
default="0.30", # this must not be transformed to float
apply_default_on_none=True,
),
]

config.validators.register(*validators)
config.validators.validate()


print(type(config.version))
print(config.version)


assert config.version == "0.30"
assert isinstance(config.version, str)
Empty file.

0 comments on commit b528e92

Please sign in to comment.