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

Fix serialization of NameEmail if name includes an email address #8860

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
3 changes: 3 additions & 0 deletions pydantic/networks.py
Expand Up @@ -502,6 +502,9 @@ def _validate(cls, __input_value: NameEmail | str) -> NameEmail:
return cls(name, email)

def __str__(self) -> str:
if '@' in self.name:
return f'"{self.name}" <{self.email}>'

return f'{self.name} <{self.email}>'


Expand Down
14 changes: 14 additions & 0 deletions tests/test_networks.py
@@ -1,3 +1,4 @@
import json
from typing import Union

import pytest
Expand Down Expand Up @@ -867,3 +868,16 @@ class Model(BaseModel):
assert exc_info.value.errors() == [
{'input': 1, 'loc': ('v',), 'msg': 'Input is not a valid NameEmail', 'type': 'name_email_type'}
]


@pytest.mark.skipif(not email_validator, reason='email_validator not installed')
def test_name_email_serialization():
class Model(BaseModel):
email: NameEmail

m = Model.model_validate({'email': '"name@mailbox.com" <name@mailbox.com>'})
assert m.email.name == 'name@mailbox.com'
assert str(m.email) == '"name@mailbox.com" <name@mailbox.com>'

obj = json.loads(m.model_dump_json())
Model(email=obj['email'])