Skip to content

Allow a type of Zero #5203

Closed
Closed
@LivInTheLookingGlass

Description

@LivInTheLookingGlass

I am requesting a feature. Often people want to be able to sum() their value types together. This is made easiest if their value types can accept an addition of 0. But the signature on such a method implies that it can accept any integer, which is false. The smallest working example would be:

from typing import Union


class Value(object):
    def __init__(self, val: int) -> None:
        self._value = val

    def __add__(self, other: Union[int, 'Value']) -> 'Value':
        if isinstance(other, Value):
            return Value(self._value, other._value)
        elif other == 0:
            return self
        else:
            return NotImplemented

sum((Value(1), Value(3))

It would be nice if this code could instead be written as:

from typing import Union, Zero


class Value(object):
    def __init__(self, val: int) -> None:
        self._value = val

    def __add__(self, other: Union[Zero, 'Value']) -> 'Value':
        if isinstance(other, Value):
            return Value(self._value, other._value)
        elif other == 0:
            return self
        else:
            return NotImplemented

sum((Value(1), Value(3))

This more clearly communicates the intent of the method.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions