python / python/mypy

overload + decorator to transform callable into class protocol w/ attribute does not see the attribute

Open
#18,715 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report
Trying to combine function attributes (a la #2087) where we add the attribute with a decorator fails to apply the decorator and the attribute is dropped on the ground.

To Reproduce

from __future__ import annotations
from typing import overload, Callable, TypeVar, Protocol
from typing_extensions import ParamSpec, reveal_type

P = ParamSpec("P")
R = TypeVar("R", covariant=True)

class WithExtra(Protocol[P, R]):
    extra: str
    def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ...

def add_extra(func: Callable[P, R]) -> WithExtra[P, R]:
    func.extra = "added"  # type: ignore
    return func  # type: ignore

@overload
@add_extra
def foo(x: int) -> str: ...

@overload
@add_extra
def foo(x: str) -> str: ...

@add_extra
def foo(x: int | str) -> str:
    return str(x)

assert foo.extra  # type: ignore[attr-defined]
reveal_type(foo)  # Revealed type is "Overload(def (x: builtins.int) -> builtins.str, def (x: builtins.str) -> builtins.str)"

This works in pyright.
I feel like it should be possible to work around it with a callable class, but I've yet to figure out the proper incantation.

Real-life use: https://github.com/pytest-dev/pytest/blob/b0caf3d7adc45f773177424593431869fd2f82d8/src/_pytest/python_api.py#L1025

Your Environment

  • Mypy version used: 1.14.1
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: python 3.13.1

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 supplied reproduction with mypy 1.14.1 and verify the revealed overload type and missing extra attribute. Trace the overload and decorator type-analysis paths to identify where the callable protocol information is lost, then add a regression test showing the expected attribute-aware result.

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
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.