Message270048
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? |
|
Date |
User |
Action |
Args |
2016-07-09 15:20:16 | ethan.furman | set | recipients:
+ ethan.furman, barry, eli.bendersky, John Hagen |
2016-07-09 15:20:16 | ethan.furman | set | messageid: <1468077616.66.0.686812215441.issue26988@psf.upfronthosting.co.za> |
2016-07-09 15:20:16 | ethan.furman | link | issue26988 messages |
2016-07-09 15:20:15 | ethan.furman | create | |
|