8000 Add a test assertion that `default_factory` can return a singleton (#… · ag-python/pydantic@827388b · GitHub
[go: up one dir, main page]

Skip to content

Commit 827388b

Browse files
Add a test assertion that default_factory can return a singleton (pydantic#1523)
1 parent 1bff804 commit 827388b

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

changes/1523-therefromhere.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add a test assertion that `default_factory` can return a singleton

tests/test_dataclasses.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,23 @@ class User:
431431
assert fields['aliases'].default == {'John': 'Joey'}
432432

433433

434+
def test_default_factory_singleton_field():
435+
class MySingleton:
436+
pass
437+
438+
class MyConfig:
439+
arbitrary_types_allowed = True
440+
441+
MY_SINGLETON = MySingleton()
442+
443+
@pydantic.dataclasses.dataclass(config=MyConfig)
444+
class Foo:
445+
singleton: MySingleton = dataclasses.field(default_factory=lambda: MY_SINGLETON)
446+
447+
# Returning a singleton from a default_factory is supported
448+
assert Foo().singleton is Foo().singleton
449+
450+
434451
def test_schema():
435452
@pydantic.dataclasses.dataclass
436453
class User:

tests/test_main.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1087,6 +1087,20 @@ class FunctionModel(BaseModel):
10871087
m = FunctionModel()
10881088
assert m.uid is uuid4
10891089

1090+
# Returning a singleton from a default_factory is supported
1091+
class MySingleton:
1092+
pass
1093+
1094+
MY_SINGLETON = MySingleton()
1095+
1096+
class SingletonFieldModel(BaseModel):
1097+
singleton: MySingleton = Field(default_factory=lambda: MY_SINGLETON)
1098+
1099+
class Config:
1100+
arbitrary_types_allowed = True
1101+
1102+
assert SingletonFieldModel().singleton is SingletonFieldModel().singleton
1103+
10901104

10911105
@pytest.mark.skipif(sys.version_info < (3, 7), reason='field constraints are set but not enforced with python 3.6')
10921106
def test_none_min_max_items():

0 commit comments

Comments
 (0)
0