Skip to content

Enum-like user classes #4311

Closed
Closed
@orenbenkiki

Description

@orenbenkiki

Feature request: Allow annotating a class as enum-like for mypy type checking purposes.

I have classes dealing with a value-like (immutable) type.
One of the classes in that family is an enum-like class, whose values are of the new immutable type.
I tried to implement this by deriving from the standard library Enum, but it has pretty strong opinions about the implementation which do not match the way my value type works (it is too different from a plain integer).

No worries, I just implemented my own MyEnumBase base class (and MyEnumMeta for it), loosely inspired by Enum.
It works fine.

The problem is convincing mypy to type check it.
Specifically, if I write:

class EnumExample(MyEnumBase):
    FOO = MyAuto()

Then mypy will not recognize that EnumExample.FOO has the type EnumExample.
I can work around this by the following horrible hack:

class IsEnumBase:
    """Check whether a given class is an enumerated base class."""
    def __eq__(self, class_name: Any) -> bool:
        return class_name == 'enum.Enum' or class_name == 'my.module.MyEnumBase'

mypy.nodes.ENUM_BASECLASS = IsEnumBase()

Which mostly works, but, shudder (is there a better way to achieve the same effect?)

It would be nice if I could annotate MyEnumBase somehow to let mypy it is an enum base class.
For example, if the single mypy.nodes.ENUM_BASECLASS was replaced by a set of class names, so that it were possible to insert additional class names into it (and provide a command line flag to mypy for doing that).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions