[Python-Dev] PEP 435 - ref impl disc 2 (original) (raw)
Glenn Linderman v+python at g.nevcal.com
Sun May 5 08:31:13 CEST 2013
- Previous message: [Python-Dev] PEP 435 - reference implementation discussion
- Next message: [Python-Dev] PEP 435 - ref impl disc 2
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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>
- Previous message: [Python-Dev] PEP 435 - reference implementation discussion
- Next message: [Python-Dev] PEP 435 - ref impl disc 2
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]