Skip to content

Commit

Permalink
Fix serialization of NameEmail if name includes an email address (#8860)
Browse files Browse the repository at this point in the history
  • Loading branch information
NeevCohen committed Feb 23, 2024
1 parent 16edb69 commit deeb110
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
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'])

0 comments on commit deeb110

Please sign in to comment.