[Python-Dev] PEP 435 - ref impl disc 2
Ethan Furman
ethan at stoneleaf.us
Tue May 7 03:26:56 CEST 2013
On 05/05/2013 01:01 AM, Glenn Linderman wrote:
>
> The bigger problem is that the arithmetic on enumeration items, which seems like it should be inherited from NamedInt
> (and seems to be, because the third value from each print is a NamedInt), doesn't pick up "x" or "y", nor does it pick
> up "the-x" or "the-y", but rather, it somehow picks up the str of the value.
Indeed, the bigger problem is that we ended up have an (NamedInt, Enum) wrapping a NamedInt, so we had both
NEI.x._intname /and/ NEI.x.value._intname, and it was just one big mess.
But I think it is solved. Try the new code. Here's what your example should look like:
class NamedInt( int ):
def __new__( cls, *args, **kwds ):
_args = args
name, *args = args
if len( args ) == 0:
raise TypeError("name and value must be specified")
self = int.__new__( cls, *args, **kwds )
self._intname = name
return self
@property
def __name__( self ):
return self._intname
def __repr__( self ):
# repr() is updated to include the name and type info
return "{}({!r}, {})".format(type(self).__name__,
self.__name__,
int.__repr__(self))
def __str__( self ):
# str() is unchanged, even if it relies on the repr() fallback
base = int
base_str = base.__str__
if base_str.__objclass__ is object:
return base.__repr__(self)
return base_str(self)
# for testing, we only define one operator that propagates expressions
def __add__(self, other):
temp = int( self ) + int( other )
if isinstance( self, NamedInt ) and isinstance( other, NamedInt ):
return NamedInt(
'({0} + {1})'.format(self.__name__, other.__name__),
temp )
else:
return temp
class NEI( NamedInt, Enum ):
x = ('the-x', 1 )
y = ('the-y', 2 )
NEI.x + NEI.y
--
~Ethan~
More information about the Python-Dev
mailing list