Search code examples
pythonpython-typingmypy

Python typing error when incrementing a dict value: 'Unsupported operand types for + ("object" and "int")'


I have this code:

result = {"AAA": "a", "BBB": "b", "Count": 0}
result["Count"] += 1

mypy generates this error message:

Unsupported operand types for + ("object" and "int")

What are some easy ways to fix this?


Solution

  • You can define the expected shape of the dictionary by defining a TypedDict:

    from typing import TypedDict
    
    class ResultDict(TypedDict):
        AAA: str
        BBB: str
        Count: int
    
    result: ResultDict = {"AAA": "a", "BBB": "b", "Count": 0}
    result["Count"] += 1
    

    In practice, it's generally easier to use a dataclasses.dataclass when you want to collect different types of data under specific names in a single object in a type-safe way. The syntax looks different but you get essentially the same functionality:

    from dataclasses import dataclass
    
    @dataclass
    class Result:
        AAA: str
        BBB: str
        Count: int
    
    result = Result(AAA="a", BBB="b", Count=0)
    result.Count += 1