python / python/mypy

Typing with ClassVar[Optional[Callable]] doesn't work if the callable has arguments

Open
#15,026 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Typing an attribute in a base class with ClassVar[Optional[Callable]] results in a type error even though the typing is seemingly sound.

To Reproduce

Playground: https://mypy-play.net/?mypy=master&python=3.11&gist=4f52f561801eeb053b6d0a47c9afbc15

class BaseClass:
    attr: ClassVar[Optional[Callable]] = None

class ChildClass2(BaseClass):
    @staticmethod
    def attr(s: str):
        pass

Expected Behavior

Mypy shouldn't return any errors.

Additionally, the same should happen when Callable is also typed itself, e.g. Callable[[str], None]. Right now both fail when they shouldn't.

Actual Behavior

test.py:10: error: Signature of "attr" incompatible with supertype "BaseClass"  [override]

Your Environment

  • Mypy version used: 1.1.1, 1.2
  • Mypy command-line flags: no relevant options
  • Mypy configuration options from mypy.ini (and other config files): no relevant options
  • Python version used: 3.11

Additional information

Interestingly, if the callable doesn't have any arguments, mypy doesn't fail:

class BaseClass:
    attr: ClassVar[Optional[Callable]] = None

class ChildClass2(BaseClass):
    @staticmethod
    def attr():
        pass

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 with the linked mypy-play reproduction using Python 3.11 and compare the untyped and typed Callable cases. Trace the override-checking path for a ClassVar Optional Callable and verify that both staticmethod examples produce no incompatible-signature error.

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
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.