[issue45473] Enum: add "name" and "value" keywords to call syntax

Ethan Furman report at bugs.python.org
Fri Oct 15 09:53:38 EDT 2021


Ethan Furman <ethan at stoneleaf.us> added the comment:

> Are there any other names that you would contemplate besides `from_name` and
> `from_value`?

No.

> My reading of your response indicates that you are fundamentally opposed to
> the addition of class methods, since they would limit the space of possible
> instance methods/members.  Is that a fair reading?

Yes.

Instance methods/attributes are not an issue, though, as the instance namespace and the class namespace are distinct -- which is why we can have a `value` member even though each member has a `value` attribute.

The issue is that class methods/attributes and members (which look like attributes) all live in the class namespace, so we cannot have both a `from_value` member and a `from_value` class method in the class namespace.

> Do you agree with the fundamental issue that is identified: that the
> parenthesis/square bracket construction is difficult to read and makes
> implementation mistakes more likely?

Only partially.  Being able to easily tell the difference between round and square brackets is an important skill to have.  With enums, square brackets are akin to dictionary lookup, which uses (string) keys, and the keys of an enum are the member names; that leaves round brackets (parenthesis), which is call syntax, for value lookup.

Additionally, if the wrong syntax is used then an exception will be raised at that location, making it an easy  fix.

> One alternative to the class methods I might propose is to use a keyword
> argument in the __init__ function.
>
>    SomeEnum(name="foo")
>    SomeEnum(value="bar")
>
> This would also solve the stated problem, but I suspect that messing with the
> init function introduces more limitations to the class than the classmethod
> solution.

This idea has come up before.  I'll look into it.

----------
title: Enum add "from_name" and "from_value" class methods -> Enum: add "name" and "value" keywords to call syntax

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45473>
_______________________________________


More information about the Python-bugs-list mailing list