BeanieODM / beanie

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

[BUG] type annotation for init_beanie() should use Sequence #911

Open entropymatters opened 3 months ago

entropymatters commented 3 months ago

Describe the bug The current annotation of init_beanie() is:

async def init_beanie(
    database: AsyncIOMotorDatabase = None,
    connection_string: Optional[str] = None,
    document_models: Optional[
        List[Union[Type[Document], Type["View"], str]]
    ] = None,
    allow_index_dropping: bool = False,
    recreate_views: bool = False,
    multiprocessing_mode: bool = False,
): ...

I.e. it uses List for the document_models argument.

To Reproduce

import asyncio

from motor import motor_asyncio
from beanie import Document, init_beanie

### these will come from other modules
class Sample(Document):
    name: str

class Another(Document):
    greeting: str

some_models = [Sample]
more_models = [Another]
###

DOCUMENT_MODELS = [
    *some_models,
    *more_models,
]

async def main() -> None:
    client = motor_asyncio.AsyncIOMotorClient('mongodb://mongo')
    database = client['mydatabase']
    await init_beanie(database=database, document_models=DOCUMENT_MODELS)

if __name__ == '__main__':
    asyncio.run(main())

Expected behavior Code type checks using mypy

Actual behaviour

error: Argument "document_models" to "init_beanie" has incompatible type "list[type[Document]]"; expected "list[type[Document] | type[View] | str] | None"  [arg-type]
note: "List" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance
note: Consider using "Sequence" instead, which is covariant

Note that DOCUMENT_MODELS is generally compatible with with the expectation, but using List and Union here appears to result in this error. IMHO, this can be fixed by using Sequence instead, since this is an argument.

I'd be glad to provide a PR if this would fix the issue.

Additional context none