[Python-ideas] Allow Enum members to refer to each other during execution of body

Ethan Furman ethan at stoneleaf.us
Tue Jul 9 04:46:18 CEST 2013


On 07/08/2013 06:03 PM, Haoyi Li wrote:
On 07/08/2013 Ethan Furman wrote:
>>
>> then the other methods can either dereference the name with an __getitem__
>> look-up, or the class can be post-processed with a decorator to change the
>>  strings back to actual members... hmmm, maybe a post_process hook in the
>> metaclass would make sense?
>
> Having real strings be part of the enums data members is a pretty common
> thing, and working through and trying to identify the linkage-strings from
>  normal-strings seems very magical to me. Is there some metaclass-magic way
> to intercept the usage of A, to instead put the enum instance there?

The post-processing routines would be specific to this enumeration, so they
should know which strings are enum references and which aren't.


> Also, for this to be useful for your described use case, (state machines yay!) you'd probably want to be able to define
> back/circular references, which i think isn't currently possible. The obvious thing to do would be to somehow make the
> RHS of the assignments lazy, which would allow out-of-order and circular assignments with a very nice, unambigious:
>
> class StateMachine(Enum):
>      "Useless ping-pong state machine"
>      A = {1: B}
>      B = {1: A}
>
> But short of using macros to do an AST transform, I don't know if such a thing is possible at all.

Starting off with strings and post-processing would handle it nicely.

--
~Ethan~


More information about the Python-ideas mailing list