Supporting Descriptors that override the Implicit Receiver Parameter

Apologies in advance if this sounds more like a bug report than a discussion, however, I was wondering if it would be possible for static type checkers to support descriptors that modify the type passed to the first parameter of a method.

For example, in a normal instance method, the type Self@ClassName is passed to the first parameter (which is by convention called self). However, you could decorate that method with a descriptor that changes the type bound to that first parameter. I think it’s best explained with a few examples.

Examples

Here, I’ve made a simplified copy of the built-in classmethod descriptor.

from typing import Callable, Concatenate
from types import MethodType

type ClassMethodType[Cls: type, **Parameters, ReturnType] = Callable[Concatenate[Cls, Parameters], ReturnType]

class ClassMethodCopy[Cls: type, **Parameters, ReturnType]:
    def __init__(self, f: ClassMethodType[Cls, Parameters, ReturnType]):
        self.f = f
        
    def __get__(self, instance: Cls | None, owner: type[Cls]):
        return MethodType(self.f, owner)
    
class Example:
    @ClassMethodCopy
    def method(cls):
        print(f"Class = {cls}")

At runtime, this works perfectly fine. However, both pyright and mypy (and I would assume other type checkers as well) reject this, as “type[Cls@ClassMethodCopy] is incompatible with Self@Example”.

You can however make this work by inserting a line after @ClassMethodCopy with a normal @classmethod.


Another example here, is a descriptor that passes a random number from 1 to 5 as the first parameter of the method.

from typing import Callable, Concatenate
from types import MethodType
from random import randint

class RNGMethod[**Parameters, ReturnType]:
    def __init__(self, f: Callable[Concatenate[int, Parameters], ReturnType]):
        self.f = f
        
    def __get__(self, instance: object | None, owner: type) -> MethodType:
        return MethodType(self.f, randint(1,5))
    
class Example:
    @RNGMethod
    def method(num) -> None:
        print(f"Number = {num}")

At runtime, this also works perfectly fine. However, once again, both pyright and mypy reject this as "int is incompatible with Self@Example. Also, like the previous example, this can be fixed by inserting the line @staticmethod after @RNGMethod.

Proposal

Although both of these can be fixed with the built-in classmethod and staticmethod decorators, I would argue that these type annotations are technically correct and shouldn’t be rejected by a static type checker, because they detail the actual type passed as arguments to these parameters.

I don’t know the source of these type checkers very well, but from what I’ve seen, and from what AI has analysed, these type checkers seem to evaluate which sort of method a method is (instance/class/static method) and infer the type of the first parameter (Self/type[Self]/Any - inferred from code) WITHOUT checking if this is modified by any descriptor. Therefore, when I decorate these methods and change the bound type of the first parameter, it evaluates the new type hint as an error rather than the correct type.

P.S. I was advised to send a discussion here as it wasn’t solely a problem with 1 type checker, apologies if this is not the sort of content to be posted here. Thank you :slight_smile:

2 Likes

These behaviors are not currently specified in the typing spec or conformance suite, so behavior will differ between type checkers. For example, in ty, which I work on, your first example already type-checks, and your second example type-checks if you type-annotate the num argument (e.g. num: int). (Leaving it un-annotated causes ty to assume that it’s an implicit self argument, and attach the type of the containing class to it.)

So although this is a perfectly on-topic post for this forum (and welcome!), I think in fact this is an appropriate topic to take up directly on the bug tracker of mypy and/or pyright, if you’d like those checkers to better support this pattern.

We could discuss here whether this behavior should be explicitly supported in the typing spec.

2 Likes

Thank you for the informative response!

I would argue that, while it is a very limited use case, it should be included in the typing spec. Type checkers are supposed to somewhat reflect the type of the objects at runtime, and in this case many type checkers are misevaluating it.

Obviously the wording would need to change, but at the link below, I believe some sort of note should be made about evaluating the type of the first parameter before defaulting the type annotations to Self / type[Self].

Thoughts?

Also, another (maybe more common) use case, and the reason I discovered this, is with descriptors. When making a library that provides classproperty descriptors (properties for class attributes), the same issue arised when trying to use the library.

Simplified:

from collections.abc import Callable

type GetterMethod[Cls, Value] = Callable[type[Cls], Value]

class classproperty[Cls, Value]:
    def __init__(fget: GetterMethod[Cls, Value]):
        self.fget = fget

    def __get__(self, instance: Cls | None, owner: type[Cls]):
        return self.fget(owner)

When attempting to implement:

class Example:
    @classproperty
    def x(cls):
        return "x"

Raises an issue with pylance and mypy as type Self is incompatible with type type[Cls@classproperty].