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

Feature / Fix: Allow Settings to be inherited and extended (fixes #644) #960

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"
Loading