Ethan Furman added the comment:

There is one wrinkle with auto-numbering.  Consider the following code:

class Color(AutoNumberEnum):
  red
  green
  blue
  @property
  def cap_name(self):
    return self.name.upper()

What happens with `property`?

- `property` is looked up in the class namespace
- it's not found, so is given the number 4
- it's then called to handle `cap_name`
- an exception is raised

As far as I can tell there is only one "good" way around this:

- store any names you don't want auto-numbered into an `_ignore_`
  attribute (this only needs to be global and built-in names that
  are used before the first method is defined)

another option is to build a proxy around any found global/built-in objects and 
decide what to do based on whether those objects are immediately called, but 
that fails when the object is simply assigned for later use.

So, barring any other ideas to handle this problem, the above example should 
look like this:

class Color(AutoNumberEnum):
  _ignore_ = 'property'
  red
  green
  blue
  @property
  def cap_name(self):
    return self.name.upper()

Another advantage of using ignore is the ability to have temporary variables 
automatically discarded:

  class Period(timedelta, Enum):
    '''
    different lengths of time
    '''
    _ignore_ = 'Period i'
    Period = vars()
    for i in range(31):
      Period['day_%d' % i] = i, 'day'
    for i in range(15):
      Period['week_%d' % i] = i*7, 'week'
    for i in range(12):
      Period['month_%d' % i] = i*30, 'month'
    OneDay = day_1
    OneWeek = week_1
    def __new__(self, value, period):
      ...

and the final enumeration does not have the temp variables `Period` nor `i`.

Thoughts?

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue26988>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to