Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Empty string is a valid JSON-key #4252

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/4253-sergeytsaplin.md
@@ -0,0 +1 @@
Allow empty string aliases by using a `alias is not None` check, rather than `bool(alias)`
6 changes: 3 additions & 3 deletions pydantic/fields.py
Expand Up @@ -148,7 +148,7 @@ def __init__(self, default: Any = Undefined, **kwargs: Any) -> None:
self.default = default
self.default_factory = kwargs.pop('default_factory', None)
self.alias = kwargs.pop('alias', None)
self.alias_priority = kwargs.pop('alias_priority', 2 if self.alias else None)
self.alias_priority = kwargs.pop('alias_priority', 2 if self.alias is not None else None)
self.title = kwargs.pop('title', None)
self.description = kwargs.pop('description', None)
self.exclude = kwargs.pop('exclude', None)
Expand Down Expand Up @@ -394,8 +394,8 @@ def __init__(
) -> None:

self.name: str = name
self.has_alias: bool = bool(alias)
self.alias: str = alias or name
self.has_alias: bool = alias is not None
self.alias: str = alias if alias is not None else name
self.type_: Any = convert_generics(type_)
self.outer_type_: Any = type_
self.class_validators = class_validators or {}
Expand Down
10 changes: 10 additions & 0 deletions tests/test_aliases.py
Expand Up @@ -335,3 +335,13 @@ def alias_generator(x):
'd_config_parent',
'e_generator_child',
]


def test_empty_string_alias():
class Model(BaseModel):
empty_string_key: int = Field(alias='')

data = {'': 123}
m = Model(**data)
assert m.empty_string_key == 123
assert m.dict(by_alias=True) == data