odmantic icon indicating copy to clipboard operation
odmantic copied to clipboard

Using the union operator in model breaks

Open iamKunal opened this issue 1 year ago • 1 comments

Bug

Using the union operator | within a model's Field type, breaks in pydantic with TypeError: type 'types.UnionType' is not subscriptable

Current Behavior

Add a model with the union operator:

class Media(Model):
  value: str | None = None

The code currently fails with:

    class Media(Model):
  File "/Users/c718230/.virtualenvs/rg-bff-backend/lib/python3.11/site-packages/odmantic/model.py", line 490, in __new__
    mcs.__validate_cls_namespace__(name, namespace)
  File "/Users/c718230/.virtualenvs/rg-bff-backend/lib/python3.11/site-packages/odmantic/model.py", line 334, in __validate_cls_namespace__
    parse_obj_as(field_type, value)
  File "pydantic/tools.py", line 37, in pydantic.tools.parse_obj_as
  File "pydantic/tools.py", line 30, in pydantic.tools._get_parsing_type
  File "pydantic/main.py", line 1026, in pydantic.main.create_model
  File "pydantic/main.py", line 178, in pydantic.main.ModelMetaclass.__new__
  File "pydantic/typing.py", line 408, in pydantic.typing.resolve_annotations
  File "/opt/homebrew/Cellar/[email protected]/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/typing.py", line 377, in _eval_type
    t = t.__origin__[args]
        ~~~~~~~~~~~~^^^^^^
TypeError: type 'types.UnionType' is not subscriptable

On the other hand using Optional[str] works as expected.

Expected behavior

Should have worked normally

Environment

  • ODMantic version: 0.9.2
  • MongoDB version: 6.0.6
  • Pydantic infos (output of python -c "import pydantic.utils; print(pydantic.utils.version_info())):
               pydantic version: 1.10.8
              pydantic compiled: True
                   install path: /Users/c718230/.virtualenvs/rg-bff-backend/lib/python3.11/site-packages/pydantic
                 python version: 3.11.3 (main, Apr  7 2023, 20:13:31) [Clang 14.0.0 (clang-1400.0.29.202)]
                       platform: macOS-13.0-arm64-arm-64bit
       optional deps. installed: ['dotenv', 'email-validator', 'typing-extensions']
    
    

Additional context

NA

EDIT

Confirmed the issue is also on normal models

iamKunal avatar Jun 01 '23 13:06 iamKunal

I had the same issue. Not sure if it's odmantic or pydantic related, but here's a workaround that works for me in case you have something that's a union of 2 types other than NoneType:

from typing import Union

class Foo(Model):
    bar: Union[int, float] = None

duhby avatar Jan 05 '24 07:01 duhby