Search code examples
pythonmarshmallow

Why dict() instead of Dict() for a marshamllow Schema?


Cannot define Dict() as field for a marshmallow-model Schema.

from marshmallow.fields import Dict
from typing import Dict
....
class OutSchema(Schema):
    queryID = String()
    img_path = String()
    object_detection = Boolean,
    visual_relations = Boolean,
    output = Dict()

Error when executing:

    Traceback (most recent call last):
      File "myfile.py", line 81, in <module>
        class EnrichmentOutSchema(Schema):
      File "myfile.py", line 86, in OutSchema
        output = Dict()
      File "/usr/lib/python3.8/typing.py", line 727, in __call__
        raise TypeError(f"Type {self._name} cannot be instantiated; "
    TypeError: Type Dict cannot be instantiated; use dict() instead

If I change Dict() for dict (as Exception says) it works. The question is, Why? Dict() is a marshmallow field, see. The following class works.

from marshmallow.fields import Dict
from typing import Dict

    class OutSchema(Schema):
        queryID = String()
        img_path = String()
        object_detection = Boolean,
        visual_relations = Boolean,
        output = dict()

Solution

  • What you are importing is typing.Dict not marshmallow.fields.Dict

    When importing anything with the same name from different modules, you can use 'as' for naming different:

    from marshmallow.fields import Dict as MarshmallowDict
    from typing import Dict
    
        class OutSchema(Schema):
            queryID = String()
            img_path = String()
            object_detection = Boolean,
            visual_relations = Boolean,
            output = MarshmallowDict()