[Python-Dev] PEP 435 - ref impl disc 2
Glenn Linderman
v+python at g.nevcal.com
Sun May 5 08:31:13 CEST 2013
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)'.
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.
class NamedInt( int ):
_count = 0
def __new__( cls, *args, **kwds ):
name, *args = args
if len( args ) == 0:
args = [ cls._count ]
cls._count += 1
self = super().__new__( cls, *args, **kwds )
self._name = name
return self
def __init__( self, *args, **kwds ):
name, *args = args
super().__init__()
@property
def __name__( self ):
return self._name
def __repr__( self ):
# repr() is updated to include the name and type info
return "{}({!r}, {})".format(type(self).__name__,
self.__name__,
super().__repr__())
def __str__( self ):
# str() is unchanged, even if it relies on the repr() fallback
base = super()
base_str = base.__str__
if base_str.__objclass__ is object:
return base.__repr__()
return base_str()
# for simplicity, 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
x = NamedInt('the-x', 1 )
y = NamedInt('the-y', 2 )
# demonstrate that NamedInt propagates the names into an expression syntax
print( repr( x ), repr( y ), repr( x+y ))
from ref435 import Enum
# requires redundant names, but loses names in the expression
class NEI( NamedInt, Enum ):
x = NamedInt('the-x', 1 )
y = NamedInt('the-y', 2 )
print( repr( NEI( 1 )), repr( NEI( 2 )), repr( NEI(1) + NEI(2)))
# looks redundant, and still loses the names in the expression
class NEI2( NamedInt, Enum ):
x = x
y = y
print( repr( NEI2( x )), repr( NEI2( x )), repr( NEI2(x) + NEI2(y)))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20130504/31397dda/attachment.html>
More information about the Python-Dev
mailing list