Make classproperty descriptor work

Open
#2,563 4 comments 10 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

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

Research direction

Start with the minimal classproperty example in the issue and read the discussion in #2266. Trace how mypy infers the decorator argument and the type of C.foo, then add coverage for this example. Done means the classproperty definition is accepted and reveal_type(C.foo) reports int rather than classproperty[None, int].

Written by the indexing model from the issue text.

Description

bug false-positive priority-1-normal topic-descriptors

As discussed in #2266, this apparently doesn't work yet:

# See http://stackoverflow.com/questions/3203286/how-to-create-a-read-only-class-property-in-python

from typing import *

T = TypeVar('T')
V = TypeVar('V')

class classproperty(Generic[T, V]):

    def __init__(self, getter: Callable[[Type[T]], V]) -> None:
        self.getter = getter

    def __get__(self, instance: Any, owner: Type[T]) -> V:
        # instance is really None, but we don't care
        return self.getter(owner)

class C:
    @classproperty    # <-- error here
    def foo(cls) -> int:
        return 42

reveal_type(C.foo)

@gvanrossum reported the following output from mypy:

classprop.py: note: In class "C":
classprop.py:20: error: Argument 1 to "classproperty" has incompatible type Callable[[C], int]; expected Callable[[Type[None]], int]
classprop.py: note: At top level:
classprop.py:25: error: Revealed type is 'classprop.classproperty[builtins.None, builtins.int*]'
Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

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.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.