python / python/mypy

Decorator doesn't preserve type

Open
#15,406 3 comments 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

In the playground

I have a decorator decorating a method (Parser.definition()) that returns a union of several Node subclasses or None. I would expect that the return type of the decorated method would be preserved (which it is in pyright), but in fact mypy simplifies it to Node | None. This is not illegal (I guess it's a valid substitution, in a sense, and the typevar's bound is Node), but it's unexpected, and not what I want: I have a call site where I have an exhaustive match p.definition() that enumerates the union elements, and the case _: assert_never(...) gives an error because the deduced type of p.definition() could be some other subclass of Node (but I know it isn't).

Any help on how to annotate the decorator in a way that preserves the type of the decorated method?

from typing import *

P = TypeVar("P", bound="Parser")
N = TypeVar("N", bound="Node")

def contextual(func: Callable[[P], N | None]) -> Callable[[P], N | None]:
    def contextual_wrapper(self: P) -> N | None:
        ...
    return contextual_wrapper

class Node:
    pass

class InstDef(Node):
    ...
    
class Macro(Node):
    ...
    
class Family(Node):
    ...

class Parser:
    @contextual
    def definition(self) -> InstDef | Macro | Family | None:
        ...

p = Parser()
reveal_type(p.definition())

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 example, focusing on the contextual decorator, Parser.definition(), and the reveal_type result. Trace how mypy infers the decorated method's return type, then verify that the declared union remains preserved and supports the exhaustive match case.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.