CopyPastor

Detecting plagiarism made easy.

Score: 1; Reported for: Exact paragraph match Open both answers

Possible Plagiarism

Plagiarized on 2025-07-29
by user118967

Original Post

Original - Posted on 2022-11-03
by STerliakov



            
Present in both answers; Present only in the new answer; Present only in the old answer;

This answer to a similar question points out that Python 3.11 offers some nice, clear alternatives to the answers listed here, including a `member` marker: <https://stackoverflow.com/a/74302109/3358488>
``` from enum import Enum, member, nonmember
def fn(x): print(x)
class MyEnum(Enum): x = nonmember(1) meth = fn mem = member(fn) @classmethod def this_is_a_method(cls): print('No, still not a member') def this_is_just_function(): print('No, not a member') @member def this_is_a_member(x): print('Now a member!', x) ```
See original answer for explanations.
Since Python 3.11 there is much more concise and understandable way. [`member` and `nonmember` functions](https://docs.python.org/3/library/enum.html#enum.member) were added to `enum` among other improvements, so you can now do the following:
```python from enum import Enum, member, nonmember
def fn(x): print(x)
class MyEnum(Enum): x = nonmember(1) meth = fn mem = member(fn) @classmethod def this_is_a_method(cls): print('No, still not a member') def this_is_just_function(): print('No, not a member') @member def this_is_a_member(x): print('Now a member!', x) ```
And now ``` >>> list(MyEnum) [<MyEnum.mem: <function fn at ...>>, <MyEnum.this_is_a_member: <function MyEnum.this_is_a_member at ...>>]
>>> MyEnum.meth(1) 1
>>> MyEnum.mem(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'MyEnum' object is not callable
>>> MyEnum.mem.value(1) 1
>>> MyEnum.this_is_a_method() No, still not a member
>>> MyEnum.this_is_just_function() No, not a member
>>> MyEnum.this_is_a_member() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'MyEnum' object is not callable
>>> MyEnum.this_is_a_member.value(1) Now a member! 1
>>> MyEnum.x 1 ```
Of course, you can add `__call__` to avoid explicit `.value` calls:
``` class MyEnum(Enum): ... def __call__(self, *args, **kwargs): return self.value(*args, **kwargs) ```
and now
``` >>> MyEnum.mem(1) 1 ```
Note that this cannot be typed correctly unless all your enum member functions share the same signature.

        
Present in both answers; Present only in the new answer; Present only in the old answer;