Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enum.nonmember Typing Issues #11921

Closed
max-muoto opened this issue May 16, 2024 · 1 comment
Closed

enum.nonmember Typing Issues #11921

max-muoto opened this issue May 16, 2024 · 1 comment

Comments

@max-muoto
Copy link
Contributor

max-muoto commented May 16, 2024

There are some issues with the typing for enum.nonmember:

import enum


class MyEnum(enum.StrEnum):
    VAL_1 = "val_1"
    VAL_2 = "val_2"

    _items = enum.nonmember({VAL_1: 1, VAL_2: 2})

    def to_int(self) -> int:
        return self._items[self]

Behavior like this is is fully supported at runtime, however, __getattr__ isn't defined on enum.nonmember, making this raise an error in Pyright. Previously, this was allowed, but now the typeshed definitions are fully relied on: microsoft/pyright#7924

Current types:

  class nonmember(Generic[_EnumMemberT]):
      def __init__(self, value: _EnumMemberT) -> None: ...
      def __getattr__(self, name: str) -> _EnumMemberT: ...

Additionally, using .value here actually does lead to a runtime error, but types for nonmember would indicate that being fine.

# Fine
MyEnum.VAL_1.to_int()

Type-checker would except this, but this fails at runtime:

import enum


class MyEnum(enum.StrEnum):
    VAL_1 = "val_1"
    VAL_2 = "val_2"

    _items = enum.nonmember({VAL_1: 1, VAL_2: 2})

    def to_int(self) -> int:
        return self._items.value[self]

#  'dict' object has no attribute 'value'
MyEnum.VAL_1.to_int()
@srittau
Copy link
Collaborator

srittau commented May 18, 2024

The stubs for nonmember are a 1:1 representation of the runtime class. The reason that this works at runtime is some magic in EnumDict:

https://github.com/python/cpython/blob/81c3130c51a2b1504842cb1a93732cc03ddbbd79/Lib/enum.py#L402-L404

This is something that the stubs can't reproduce, but needs to be hard-coded into type checkers, unfortunately.

@srittau srittau closed this as not planned Won't fix, can't repro, duplicate, stale May 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants