Skip to content

Enum plugin should support unique check where possible #10858

Open
@sobolevn

Description

@sobolevn

Feature

After #10852 is merged we can work on making @enum.unique to check for actually unique values.

Right now it does nothing. In other words, this code passes mypy check:

from enum import Enum, unique

@unique
class A(Enum):
   x = 1
   y = 1

But, fails in runtime:

Traceback (most recent call last):
  File "ex.py", line 4, in <module>
    class A(Enum):
  File "/Users/sobolev/.pyenv/versions/3.8.9/lib/python3.8/enum.py", line 969, in unique
    raise ValueError('duplicate values found in %r: %s' %
ValueError: duplicate values found in <enum 'A'>: y -> x

But, since after #10852 all fields would be implicitly final and their values will be inferred as Literal types, this gives us some space to check that we have unique literal values inside mypy/plugins/enums.py

Corner case

We should ignore any non-Literal values from this check:

def rand_int() -> int:
    ...

@unique 
class A(Enum):
    x = rand_int()
    y = rand_int()
    z = 0

This can even raise in runtime if x or y is 0, but we have no way of knowing this in advance.

Related #5599
Related #10857

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions