[Python] What is the "_Addable" type hint in Python/PyCharm? (sum() function details)

Discussão em 'Python' iniciado por Stack, Agosto 7, 2025.

  1. Stack

    Stack Membro Participativo

    I encountered the _Addable type hint when examining the sum() function in PyCharm.

    PyCharm sum() documentation

    I know sum() can add numbers in the usual way or add lists via concatenation:

    >>> list1 = list(range(1,4))
    >>> list2 = list(range(4,7))
    >>> sum(list1)
    6
    >>> L_of_L = [list1,list2]
    >>> sum(L_of_L,[])
    [1, 2, 3, 4, 5, 6]


    So it makes sense that lists as well as numbers count as "addable". However, strings support addition but sum() does not support adding them.

    >>> sum(['s','a'],'')
    Traceback (most recent call last):
    File "<input>", line 1, in <module>
    TypeError: sum() can't sum strings [use ''.join(seq) instead]


    So what exactly is the "_Addable" type? Is there a list of data structures that are "_Addable"?

    I expected to search "_Addable" and find the exact type details, but no luck on Google. Within PyCharm I found the following code in builtins.pyi.

    _AddableT1 = TypeVar("_AddableT1", bound=SupportsAdd[Any, Any])
    _AddableT2 = TypeVar("_AddableT2", bound=SupportsAdd[Any, Any])


    The bound parameter gave some clues, but again strings also support addition so I'm still unclear about what data structures satisfy "addable" in this context.

    I also read parts of PEP 483 and 484. They helped me understand type-hinting more generally but didn't answer my specific question.

    Continue reading...

Compartilhe esta Página