From a4f73d05c5bdb30c296304a35e62c042ccc2aeaf Mon Sep 17 00:00:00 2001 From: Christian Kokott Date: Tue, 2 Jul 2024 14:56:48 +0200 Subject: [PATCH 1/2] Changed the way setting class attributes are collected in order to allow for partially inheriting settings from parent classes. --- beanie/odm/utils/init.py | 12 +++++++++--- tests/odm/documents/test_init.py | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/beanie/odm/utils/init.py b/beanie/odm/utils/init.py index 1f230c9e..568d225e 100644 --- a/beanie/odm/utils/init.py +++ b/beanie/odm/utils/init.py @@ -175,9 +175,15 @@ def init_settings( :return: None """ settings_class = getattr(cls, "Settings", None) - settings_vars = ( - {} if settings_class is None else dict(vars(settings_class)) - ) + settings_vars = {} + if settings_class is not None: + # get all attributes of the Settings subclass (including inherited ones) + # without magic dunder methods + settings_vars = { + attr: getattr(settings_class, attr) + for attr in dir(settings_class) + if not attr.startswith("__") + } if issubclass(cls, Document): cls._document_settings = parse_model( DocumentSettings, settings_vars diff --git a/tests/odm/documents/test_init.py b/tests/odm/documents/test_init.py index 78db259e..2ca50591 100644 --- a/tests/odm/documents/test_init.py +++ b/tests/odm/documents/test_init.py @@ -354,3 +354,22 @@ async def test_init_document_with_union_type_expression_optional_back_link(db): "back_link_list", "back_link", } + + +async def test_init_document_can_inhert_and_extend_settings(db): + class Sample1(Document): + class Settings: + name = "sample1" + bson_encoders = {Color: lambda x: x.value} + + class Sample2(Sample1): + class Settings(Sample1.Settings): + name = "sample2" + + await init_beanie( + database=db, + document_models=[Sample2], + ) + + assert Sample2.get_settings().bson_encoders != {} + assert Sample2.get_settings().name == "sample2" From 1d8151e90ff97a6fbb4eca1c0bb0daefa9957570 Mon Sep 17 00:00:00 2001 From: Christian Kokott Date: Fri, 5 Jul 2024 10:24:34 +0000 Subject: [PATCH 2/2] Formatting to satisfy pre-commit --- tests/odm/documents/test_init.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/odm/documents/test_init.py b/tests/odm/documents/test_init.py index c0fbdefb..b87a62fd 100644 --- a/tests/odm/documents/test_init.py +++ b/tests/odm/documents/test_init.py @@ -361,7 +361,7 @@ async def test_init_document_with_union_type_expression_optional_back_link(db): } ) - + async def test_init_document_can_inhert_and_extend_settings(db): class Sample1(Document): class Settings: