Skip to content

Commit

Permalink
Merge pull request #960 from dotKokott/feat/settings-are-inheritable
Browse files Browse the repository at this point in the history
Feature / Fix: Allow Settings to be inherited and extended (fixes #644)
  • Loading branch information
adeelsohailahmed authored Aug 21, 2024
2 parents 86cbc28 + 1d8151e commit 6ebcdf4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
12 changes: 9 additions & 3 deletions beanie/odm/utils/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions tests/odm/documents/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,3 +360,22 @@ async def test_init_document_with_union_type_expression_optional_back_link(db):
"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"

0 comments on commit 6ebcdf4

Please sign in to comment.