python / python/mypy

`Enum.value` typed as `Any` when using `functools.cache`

Open
#19,368 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

If I define a method with @functools.cache on an Enum, then the type of that Enum's value attr becomes Any. Without the @functools.cache annotation, it gets typed correctly.

Also, this behavior does not occur if you use enum literals - i.e., Foo.BAR.value is typed correctly, but foo.value (for a foo: Foo) is wrong.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=b2a218b8db8367b2ac62dcf583a8c4f7

Expected Behavior

The type assertion in frobnicate() should succeed.

Actual Behavior

The type assertion in frobnicate() fails 😿.

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.12 and inspect how functools.cache affects the type of Enum.value for a variable typed as the enum. Compare this with the working enum-literal case and use the assertion in frobnicate() as the success criterion. Add a regression test covering the reported behavior.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.