BeanieODM / beanie

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

[BUG] Weird `TypeError` when calling `init_beanie` using `dict` instead of `Dict` in module #824

Open ivan-gj opened 9 months ago

ivan-gj commented 9 months ago

Using Python 3.10, one is expected to essentially not use Dict anymore, and simply utilise dict. This is also true with many other types such as tuple, etc.

This, tho, makes beanie raise a TypeError if such dict usage is done at the module level of one of the documents input to init_beanie.

To Reproduce

import asyncio
from typing import Any

from beanie import Document, init_beanie
from motor.motor_asyncio import AsyncIOMotorClient

DictStrAny = dict[str, Any]

class Thing(Document):
    thing: DictStrAny

    class Settings:
        name = "things"

async def main():
    client = AsyncIOMotorClient("mongodb://localhost:27017")

    await init_beanie(database=client["test_db"], document_models=[Thing])

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

Expected behaviour

Technically, nothing wrong has been done here, but the program crashes with the following:

Traceback (most recent call last):
  [...]
  File "[...]/beanie_crash_pydantic_v2.py", line 20, in main
    await init_beanie(database=client["test_db"], document_models=[Thing])
  File "[...]/.cache/pypoetry/virtualenvs/algo-db-manager-C0jUbCoT-py3.10/lib/python3.10/site-packages/beanie/odm/utils/init.py", line 754, in init_beanie
    await Initializer(
  File "[...]/.cache/pypoetry/virtualenvs/algo-db-manager-C0jUbCoT-py3.10/lib/python3.10/site-packages/beanie/odm/utils/init.py", line 121, in __init__
    self.fill_docs_registry()
  File "[...]/.cache/pypoetry/virtualenvs/algo-db-manager-C0jUbCoT-py3.10/lib/python3.10/site-packages/beanie/odm/utils/init.py", line 137, in fill_docs_registry
    if inspect.isclass(obj) and issubclass(obj, BaseModel):
  File "[...]/.conda/envs/python310/lib/python3.10/abc.py", line 123, in __subclasscheck__
    return _abc_subclasscheck(cls, subclass)
TypeError: issubclass() arg 1 must be a class

Additional context Using:


Current workaround

Current workaround is to either come back to use capital Dict (or equivalents) in those kinds of definitions... which goes technically against current style guides, or avoid using this kind of auxiliary definitions at all.

roman-right commented 8 months ago

Hi @ivan-gj , Thank you for the catch!