Skip to content

Conversation

@sharkdp
Copy link
Contributor

@sharkdp sharkdp commented Jul 22, 2025

Summary

Infer the correct type in a scenario like this:

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

for color in Color:
    reveal_type(color)  # revealed: Color

We should eventually support this out-of-the-box when astral-sh/ty#501 is implemented. For this reason, @AlexWaygood would prefer to keep things as they are (we currently infer Unknown, so false positives seem unlikely). But it seemed relatively easy to support, so I'm opening this for discussion.

part of astral-sh/ty#183

Test Plan

Adapted existing test.

Ecosystem analysis

- warning[unused-ignore-comment] rotkehlchen/chain/aggregator.py:591:82: Unused blanket `type: ignore` directive

This unused-ignore-comment goes away due to a new true positive.

@sharkdp sharkdp added the ty Multi-file analysis & type inference label Jul 22, 2025
@github-actions
Copy link
Contributor

mypy_primer results

Changes were detected when running on open source projects
rotki (https://github.com/rotki/rotki)
- warning[unused-ignore-comment] rotkehlchen/chain/aggregator.py:591:82: Unused blanket `type: ignore` directive
- Found 1580 diagnostics
+ Found 1579 diagnostics
No memory usage changes detected ✅

Copy link
Member

@AlexWaygood AlexWaygood left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code looks good but you already know my opinion on whether it's worth adding this branch in the first place :-)

Copy link
Member

@MichaReiser MichaReiser left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alex said the code looks good ;)

@sharkdp
Copy link
Contributor Author

sharkdp commented Jul 22, 2025

It doesn't look like a huge maintenance burden to me, so I'm merging this to complete my list of "high priority" enum tasks.

@sharkdp sharkdp merged commit da8aa6a into main Jul 22, 2025
38 checks passed
@sharkdp sharkdp deleted the david/enum-iteration branch July 22, 2025 14:09
@AlexWaygood
Copy link
Member

I suppose the logic here doesn't account for the fact that enums can have subclasses of EnumMeta as their metaclass. E.g. we reveal Foo here, but at runtime iterating over this enum class yields ints:

from typing import Iterator, reveal_type
import enum

class Annoying(enum.EnumMeta):
    def __iter__(cls) -> Iterator[int]:
        yield from range(4)

class Foo(enum.Enum, metaclass=Annoying):
    A = 1
    B = 2

for f in Foo:
    reveal_type(f)

https://play.ty.dev/3347bb64-35ba-469a-9359-b5fe504bb81d

Having said that, we'll emit a Liskov violation on Annoying.__iter__ once we've implemented astral-sh/ty#166. In fact, I don't think it's possible to override EnumMeta.__iter__ and change its return type in a Liskov-compatible way. So this probably isn't a serious issue.

@carljm
Copy link
Contributor

carljm commented Jul 22, 2025

FWIW, mypy issues the Liskov error, pyright does not. Both mypy and pyright do correctly infer that the iteration yields int in that example.

@carljm
Copy link
Contributor

carljm commented Jul 22, 2025

But I think once we fix astral-sh/ty#501 and remove this temporary approach, that should fall out anyway, so not worth worrying about now.

dcreager added a commit that referenced this pull request Jul 22, 2025
* main:
  [ty] Use `ThinVec` for sub segments in `PlaceExpr` (#19470)
  [ty] Splat variadic arguments into parameter list (#18996)
  [`flake8-pyi`] Skip fix if all `Union` members are `None` (`PYI016`)  (#19416)
  Skip notebook with errors in ecosystem check (#19491)
  [ty] Consistent use of American english (in rules) (#19488)
  [ty] Support iterating over enums (#19486)
  Fix panic for illegal `Literal[…]` annotations with inner subscript expressions (#19489)
  Move fix suggestion to subdiagnostic (#19464)
  [ty] Implement non-stdlib stub mapping for classes and functions (#19471)
  [ty] Disallow illegal uses of `ClassVar` (#19483)
  [ty] Disallow `Final` in function parameter/return-type annotations (#19480)
  [ty] Extend `Final` test suite (#19476)
  [ty] Minor change to diagnostic message for invalid Literal uses (#19482)
  [ty] Detect illegal non-enum attribute accesses in Literal annotation (#19477)
  [ty] Reduce size of `TypeInference` (#19435)
  Run MD tests for Markdown-only changes (#19479)
  Revert "[ty] Detect illegal non-enum attribute accesses in Literal annotation"
  [ty] Detect illegal non-enum attribute accesses in Literal annotation
  [ty] Added semantic token support for more identifiers (#19473)
  [ty] Make tuple subclass constructors sound (#19469)
UnboundVariable pushed a commit to UnboundVariable/ruff that referenced this pull request Jul 23, 2025
* main: (28 commits)
  [ty] highlight the argument in `static_assert` error messages (astral-sh#19426)
  [ty] Infer single-valuedness for enums based on `int`/`str` (astral-sh#19510)
  [ty] Restructure submodule query around `File` dependency
  [ty] Make `Module` a Salsa ingredient
  [ty] Reachability analysis for `isinstance(…)` branches (astral-sh#19503)
  [ty] Normalize single-member enums to their instance type (astral-sh#19502)
  [ty] Invert `ty_ide` and `ty_project` dependency (astral-sh#19501)
  [ty] Implement mock language server for testing (astral-sh#19391)
  [ty] Detect enums if metaclass is a subtype of EnumType/EnumMeta (astral-sh#19481)
  [ty] perform type narrowing for places marked `global` too (astral-sh#19381)
  [ty] Use `ThinVec` for sub segments in `PlaceExpr` (astral-sh#19470)
  [ty] Splat variadic arguments into parameter list (astral-sh#18996)
  [`flake8-pyi`] Skip fix if all `Union` members are `None` (`PYI016`)  (astral-sh#19416)
  Skip notebook with errors in ecosystem check (astral-sh#19491)
  [ty] Consistent use of American english (in rules) (astral-sh#19488)
  [ty] Support iterating over enums (astral-sh#19486)
  Fix panic for illegal `Literal[…]` annotations with inner subscript expressions (astral-sh#19489)
  Move fix suggestion to subdiagnostic (astral-sh#19464)
  [ty] Implement non-stdlib stub mapping for classes and functions (astral-sh#19471)
  [ty] Disallow illegal uses of `ClassVar` (astral-sh#19483)
  ...

# Conflicts:
#	crates/ty_ide/src/goto.rs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ty Multi-file analysis & type inference

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants