[Python] Python type annotations for functions that return a class

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    Consider the following code, which models the integers mod n:

    def IntegersModN(n):
    class InternalClass:
    def __init__(self, x):
    self.x = x % n
    def __add__(self, other):
    return self.__class__(self.x + other.x)
    def __str__(self):
    return str(self.x)
    return InternalClass

    IntegersMod5 = IntegersModN(5)
    print(IntegersMod5(4) + IntegersMod5(2)) # output: 1


    It runs fine. But suppose I wanted to add type annotations to statically ensure that I never do something like:

    IntegersMod4 = IntegersModN(4)
    IntegersMod5 = IntegersModN(5)
    print(IntegersMod4(1) + IntegersMod5(2)) # desired mypy error


    I know it's probably not possible to statically check that the mods are equal, but I was hoping that at least there was a way to differentiate every class constructed by IntegersModN. In other words, I would like each call of IntegersModN to produce a new InternalClass that only allows adding two elements of itself. In particular, the following code should also throw a mypy error:

    IntegersMod5_1 = IntegersModN(5)
    IntegersMod5_2 = IntegersModN(5)
    print(IntegersMod5_1(1) + IntegersMod5_2(2)) # desired mypy error


    Is that possible? (I tried just adding Self annotations to the arguments in __add__(self, other), but that didn't seem to do anything. Using Python 3.13.) Additionally, if not possible in Python, what other programming languages is this possible in?

    Continue reading...

Compartilhe esta Página