Proposal for adding symbols within Python
Pierre Barbier de Reuille
pierre.barbier at cirad.fr
Sun Nov 13 10:26:32 EST 2005
Ben Finney a écrit :
> Pierre Barbier de Reuille <pierre.barbier at cirad.fr> wrote:
>
>>Mike Meyer a écrit :
>>
>>>Hmm. You know, $symbol$ doesn't seem nearly as bad as $symbol. It
>>>tickles TeX, not P***. I could live with that.
>>
>>Yep, I like this $symbol$ notation !
>
>
> Gets a big -1 here.
>
> I've yet to see a convincing argument against simply assigning values
> to names, then using those names.
>
I can see three interests :
1 - ensure values are unique (i.e. a bit like using instances of object)
2 - values are meaningful (i.e. with introspection on the values you get
a human-readable value, unlike with instances of object)
3 - getting an *easy* access to those two properties
1 and 2 require a new type, 3 a new syntax (IMO).
Here's a try for the symbol class :
class symbol(object):
def __init__(self, value):
self._value = value
def _get_value(self):
return self._value
value = property(_get_value)
def __eq__(self, other):
return self.value == other.value
def __str__(self):
return str(self.value)
def __repr__(self):
return "symbol(%s)" % (repr(self.value),)
One thing to do would be to return the same object for symbols with the
same value (when possible ...).
For example, if we limit symbol to hashable types, we can implement
something which can be tested with "is" instead of "==":
class symbol(object):
_cache = {}
def __new__(cls, value):
if value in symbol._cache:
return symbol._cache[value]
self = object.__new__(cls)
self._value = value
symbol._cache[value] = self
return self
def _get_value(self):
return self._value
value = property(_get_value)
def __eq__(self, other):
return self.value == other.value
def __str__(self):
return str(self.value)
def __repr__(self):
return "symbol(%s)" % (repr(self.value),)
Then, as I suggested, you can do something like :
a = symbol((file, "opened"))
But it's less readable than $file.opened$ (or something similar).
Pierre
More information about the Python-list
mailing list