BeanieODM / beanie

Asynchronous Python ODM for MongoDB
http://beanie-odm.dev/
Apache License 2.0
2.02k stars 213 forks source link

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

Closed dotKokott closed 1 month ago

dotKokott commented 3 months ago

Before this would not work

from beanie import Document, init_beanie

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 != {} # Fails because Settings subclass completely overrides Sample1.Settings

The fastapi-users library actually claims in their documentation that this is how you should extend their BeanieBaseUser model to change the collection name: https://fastapi-users.github.io/fastapi-users/latest/configuration/databases/beanie/

Indeed the functionality would be very useful e.g. to provide shared bscon_encoders via a kind of base document model that all your documents inherit from.

This fixes https://github.com/BeanieODM/beanie/issues/644 which was closed without resolution. In the issue @roman-right mentions that this is not fixable because it would have to be fixed via metaclass which is already occupied by pydantic. Evidently, by this PR, that is not the case :)

The way the Settings attribute collection was implemented before (via vars(class)) would throw away the inherited Settings if a Settings class was present in the inheriting class.

I changed the Settings attribute collection to use dir and included some filtering of dunder methods.

✅ Tests passing
✅ Added test to cover new functionality

I don't know if this fix / feature needs a change in the Settings documentation. Arguably it now behaves the way you'd expect this to behave, as it mirrors the way these attributes access and inherit via normal Python.