Author Antony.Lee
Recipients Antony.Lee, ethan.furman
Date 2018-09-20.16:07:17
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1537459637.17.0.956365154283.issue34750@psf.upfronthosting.co.za>
In-reply-to
Content
I have a personal helper function for writing (Qt) GUIs that generates ComboBoxes from Enums; essentially something like

    class Choices(Enum):
        choice1 = "text for choice 1"
        choice2 = "text for choice 2"

    def callback(choice: Choices):
        # do stuff based on choice
        pass

    create_combobox(Choices, callback=callback)

I'm not including the actual code for create_combobox because it's not particularly relevant here.

So far, if I wanted to add methods to the Choice enum (e.g. for simplifying the code in `callback`), I could do it directly; if I wanted to dynamically generate the list of choices, I could also do it (by using the functional API).  But to do both, it would have been nice to use the locals().update approach in the bug report above.  Instead, I need to do something like

    class MethodsMixin(Enum):
        def method(self): ...

    ChoicesWithMethods = MethodsMixin("ChoicesWithMethods", [<the choices>])

(As a side note, I originally thought I could do the inheritance in the opposite direction

    Choices = Enum("Choices", [...])

    class ChoicesWithMethods(Choices):
        def method(self): ...

but that fails because Choices is a final class.  It would be nice if it was still possible to inherit from Choices *as long as only methods are added, rather than new members* (I understand why adding new members is problematic).  But this is really a side point.)

Making _EnumDict actually support update() and every other relevant method is actually not particularly difficult: I think you just need to make it inherit from (collections.abc.MutableMapping, dict) (in that order); this is exactly the approach used (since a while ago) by matplotlib's RcParams class (https://github.com/matplotlib/matplotlib/blob/v3.0.0/lib/matplotlib/__init__.py#L783).
History
Date User Action Args
2018-09-20 16:07:17Antony.Leesetrecipients: + Antony.Lee, ethan.furman
2018-09-20 16:07:17Antony.Leesetmessageid: <1537459637.17.0.956365154283.issue34750@psf.upfronthosting.co.za>
2018-09-20 16:07:17Antony.Leelinkissue34750 messages
2018-09-20 16:07:17Antony.Leecreate