Enum + new in 3.11

dn PythonList at DancesWithMice.info
Fri Jun 16 01:40:10 EDT 2023


Have you figured-out a use for the @enum.member and @enum.nonmember 
decorators (new in Python 3.11)?


"What's New" says:
Added the member() and nonmember() decorators, to ensure the decorated 
object is/is not converted to an enum member.

The PSL docs say:
@enum.member
     A decorator for use in enums: its target will become a member.

also:
enum members have names and values (the name of Color.RED is RED, the 
value of Color.BLUE is 3, etc.)

Whereas the "Utilities and Decorators" section is slightly confusing 
because class decorators are mixed with others, so one has to read 
more-carefully.


"Curiosity killed the cat" and other cautionary tales/tails...

Have added the following decorated staticmethod to a basic enum. It is 
indeed recognised as a member of the enum, but its value is the 
method-object. To gain the value the method-object represents 
(property-like behavior) one has to call the method/enum-value as a 
function:-


from enum import Enum, member


class MenuOptions( Enum ):
     """ Legal menu-choices. """
     N = "NewGame"
     L = "LoadGame"
     # ...

     @member
     @staticmethod
     def extra_member()->str:
         return "QuitGame"


def print_demo( enum_chosen:MenuOptions )->None:
     """ Illustrative printing. """
     print( "Name:", enum_chosen, enum_chosen.name )
     if isinstance( enum_chosen, MenuOptions ):
         print( "Value:", enum_chosen.value )


print( MenuOptions.__members__ )
# {'N': <MenuOptions.N: 'NewGame'>, 'L': <MenuOptions.L: 'LoadGame'>, 
'extra_member': <MenuOptions.extra_member: <staticmethod(<function 
MenuOptions.extra_member at 0x7f0802128860>)>>}

print_demo( MenuOptions[ "L" ] )
# Name: MenuOptions.L L
# Value: LoadGame

print_demo( MenuOptions.extra_member )
# Name: MenuOptions.extra_member extra_member
# Value: <staticmethod(<function MenuOptions.extra_member at 
0x7f0802128860>)>

print( MenuOptions.extra_member.value() )
# QuitGame


Therefore, like an @property decorator applied to a method in a 
custom-class, it could be used to only evaluate some 'expensive' 
computation if/when it is needed. Similarly, it could use the other 
values within the enum in order to present some 'combination'.

Weirdly (given that enums are considered immutable) I imagine that if 
the 'extra_member' were to call some external function with varying 
output, the value could be considered mutable when it is eventually called.

Other?better ideas...

-- 
Regards,
=dn


More information about the Python-list mailing list