<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body text="#330033" bgcolor="#FFFFFF">
So I have a class based on Nick's Named Values, that has been
extended to propagate names into expressions, so that if you have
named values 'x' and 'y', when you x + y, the result is a named
value whose name is '(x + y)'.<br>
<br>
Seems pretty awkward to integrate this with Enum. Maybe I'm missing
something. Here's carved down code with just one operator defined
for brevity. The third item from each print statement should be the
same, as far as I understand... but isn't.<br>
<br>
class NamedInt( int ):<br>
_count = 0<br>
def __new__( cls, *args, **kwds ):<br>
name, *args = args<br>
if len( args ) == 0:<br>
args = [ cls._count ]<br>
cls._count += 1<br>
self = super().__new__( cls, *args, **kwds )<br>
self._name = name<br>
return self<br>
def __init__( self, *args, **kwds ):<br>
name, *args = args<br>
super().__init__()<br>
@property<br>
def __name__( self ):<br>
return self._name<br>
def __repr__( self ):<br>
# repr() is updated to include the name and type info<br>
return "{}({!r}, {})".format(type(self).__name__,<br>
self.__name__,<br>
super().__repr__())<br>
def __str__( self ):<br>
# str() is unchanged, even if it relies on the repr()
fallback<br>
base = super()<br>
base_str = base.__str__<br>
if base_str.__objclass__ is object:<br>
return base.__repr__()<br>
return base_str()<br>
<br>
# for simplicity, we only define one operator that propagates
expressions<br>
def __add__(self, other):<br>
temp = int( self ) + int( other )<br>
if isinstance( self, NamedInt ) and isinstance( other,
NamedInt ):<br>
return NamedInt(<br>
'({0} + {1})'.format(self.__name__, other.__name__),<br>
temp )<br>
else:<br>
return temp<br>
<br>
x = NamedInt('the-x', 1 )<br>
y = NamedInt('the-y', 2 )<br>
# demonstrate that NamedInt propagates the names into an expression
syntax<br>
print( repr( x ), repr( y ), repr( x+y ))<br>
<br>
from ref435 import Enum<br>
<br>
# requires redundant names, but loses names in the expression<br>
class NEI( NamedInt, Enum ):<br>
x = NamedInt('the-x', 1 )<br>
y = NamedInt('the-y', 2 )<br>
<br>
print( repr( NEI( 1 )), repr( NEI( 2 )), repr( NEI(1) + NEI(2)))<br>
<br>
# looks redundant, and still loses the names in the expression<br>
class NEI2( NamedInt, Enum ):<br>
x = x<br>
y = y<br>
<br>
print( repr( NEI2( x )), repr( NEI2( x )), repr( NEI2(x) + NEI2(y)))<br>
<br>
<br>
<br>
</body>
</html>