python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.24k stars 2.79k forks source link

Inconsistent errors with custom enum base auto items from installed library #15382

Open felix-hilden opened 1 year ago

felix-hilden commented 1 year ago

Hi, I've defined a custom enum base to copy the names of the enum items as values when using auto(). Mypy curiously throws an assignment error about incompatible types when using the items as e.g. default arguments in a function. However, this only happens if the custom base is imported from another library (in site packages, using another local package is fine).

Here's some example code:

from enum import Enum, auto
# from lib import CopyNameEnum

class CopyNameEnum(Enum):
    def _generate_next_value_(name, start, count, last_values):
        return name

class Items(str, CopyNameEnum):
    A = auto()
    B = auto()

def process(item: Items = Items.A):
    pass

The above is fine and produces no errors. However, when using the import instead, we get

Incompatible default for argument "item" (default has type "auto", argument has type "Items") [assignment]

I would assume that this is a bug, but if you have any other thoughts or debugging suggestions, let me know! I found another issue about the same private method in Enum in #7591, but the issue doesn't seem to be exactly related.

Environment

Avasam commented 1 year ago

I believe _generate_next_value_ should be decorated with @staticmethod. But that crashes in python 3.8 and 3.9 . Not sure if that can be fixed on the type-definition side (see https://github.com/python/typeshed/issues/10428)