[issue31801] vars() manipulation encounters problems with Enum

Eric Wieser report at bugs.python.org
Wed Nov 15 03:24:49 EST 2017


Eric Wieser <wieser.eric+pybug at gmail.com> added the comment:

Not necessarily an argument against this feature, but two workarounds exist for this already:


1. Use `nonlocal` to prevent `value` going into the class namespace:

    value = None
    
    class BaudRate(enum.Enum):    
        nonlocal value
        for value in rates:
            locals()['B%d' % value] = value
    
        @classmethod
        def valid_rate(cls, value):
            return (any(value == item.value for item in cls))

2. Use `types.new_class`, which is more suited to dynamic class creation anyway:

    def make_cls(ns):
        for value in rates:
            ns['B%d' % value] = value

        @classmethod
        def valid_rate(cls, value):
            return (any(value == item.value for item in cls))

        ns['valid_rate'] = valid_rate

    types.new_class('BaudRate', (enum.Enum,), exec_body=make_cls)

----------
nosy: +Eric.Wieser

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


More information about the Python-bugs-list mailing list