[Python-Dev] AutoNumber Enum (original) (raw)

Ivan Levkivskyi levkivskyi at gmail.com
Wed Jun 29 16:01:11 EDT 2016


It looks like the values in AutoNumberEnum are consecutive integers 1,2,3,... Have you considered an option (keyword argument) to change this to powers of two 1,2,4,8,...?

-- Ivan

On 29 June 2016 at 21:23, Ethan Furman <ethan at stoneleaf.us> wrote:

On 06/29/2016 12:11 PM, Guido van Rossum wrote:

And how would you implement that without support from the compiler? Does it use a hook that catches the NameError?

It's built into the EnumDict class dictionary used during class creation. Current (edited) code from the aenum package that implements this: class EnumDict(dict): """Track enum member order and ensure member names are not reused. EnumMeta will use the names found in self.membernames as the enumeration member names. """ def init(self, locked=True, start=1, multivalue=False): super(EnumDict, self).init() # list of enum members self.membernames = [] # starting value for AutoNumber self.value = start - 1 # when the magic turns off self.locked = locked ... def getitem(self, key): if ( self.locked or key in self or issunder(key) or isdunder(key) ): return super(EnumDict, self).getitem(key) try: # try to generate the next value value = self.value + 1 self.setitem(key, value) return value except: # couldn't work the magic, report error raise KeyError('%s not found' % key) def setitem(self, key, value): """Changes anything not sundured, dundered, nor a descriptor. Single underscore (sunder) names are reserved. """ if issunder(key): raise ValueError('names are reserved for future Enum use') elif isdunder(key): if key == 'order': key = 'order' if isdescriptor(value): self.locked = True elif key in self.membernames: # descriptor overwriting an enum? raise TypeError('Attempted to reuse name: %r' % key) elif not isdescriptor(value): if key in self: # enum overwriting a descriptor? raise TypeError('%s already defined as: %r' % ... self.membernames.append(key) if not self.locked: if isinstance(value, int): self.value = value else: count = self.value + 1 self.value = count value = count, value else: # not a new member, turn off the autoassign magic self.locked = True super(EnumDict, self).setitem(key, value) Disclaimer: some errors may have crept in as I deleted unrelated content. For the full code check out the EnumDict class in the aenum package. -- Ethan


Python-Dev mailing list Python-Dev at python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/levkivskyi%40gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20160629/0815602a/attachment.html>



More information about the Python-Dev mailing list