python / python/mypy

Descriptor protocol is executed for properties returning descriptors

Open
#13,608 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-descriptors
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Consider this example:

from __future__ import annotations

class X: ...

class Y:
    @property
    def some_property(self) -> Descriptor: # return Descriptor instance
        return Descriptor()

class Descriptor:
    def __get__(self, obj: X, cls: type[X]) -> int: # can work only with X instances
        print(f'Descriptor.__get__({self}, {obj}, {cls}) called')
        return 0

y = Y()
print(y.some_property)
# arg-type: Argument 1 to "__get__" of "Descriptor" has incompatible type "Y"; expected "X"
# arg-type: Argument 2 to "__get__" of "Descriptor" has incompatible type "Type[Y]"; expected "Type[X]"

# stdout: <__main__.Descriptor object at 0x0000020BF8A5BE20>
# note that Descriptor.__get__ isnt called

I am defining descriptor that can work only with X instances, and i am returning this descriptor from property of Y instances.
At runtime Descriptor.__get__ isnt called, but mypy thinks that Y.some_property is Descriptor (not a property returning Descriptor instance), tries to execute descriptor protocol and fails.

At runtime i am getting no errors, descriptor isnt called and this code is safe.

To reproduce:

  • just run mypy with this code

Expected Behavior

  • no errors

Actual Behavior

  • error

Your Environment

  • Mypy version used: mypy 0.971 (compiled: yes)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10.6
  • Operating system and version: Win10

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the inline reproducer with mypy 0.971 and confirm the two descriptor-related errors. Trace mypy's handling of properties whose return values implement descriptors, then verify that the example produces no errors while genuine descriptor access remains checked.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.