Super Tuples

Antti Kuntsi kuntsi at cc.helsinki.fi.spam.no
Mon Dec 27 13:58:59 EST 1999


Paul Prescod <paul at prescod.net> sepusti:
> I propose that in Python 1.6 tuples be given the demonstrated features:
> >>> time = (hour=24, minute=00, second=00 )
> >>> print time.hour
> 24
> >>> hr, min, sec = time
> >>> print hr, min, sec
> (24, 00, 00 )
> >>> min, sec, hr = time
> >>> print min, sec, hr 
> (24, 00, 00 )
> (this last just demonstrates that tuples continue to work the way they
> always have. There is no magic about looking at the names of
> assignments)


Here is my quick attempt to do the SuperTuple. There is at least one big
problem, as I don't know how to figure out the order in which the keyword
arguments were given.

Testing, if it works:
>>> st=SuperTuple(1,2,"fish", spam=600)
>>> print st, st.spam
(1, 2, 'fish', 600) 600
>>> print st.names(), st["spam"]
['spam'] 600
>>> print ("eggs",6)+st, st+("eggs", 6)
('eggs', 6, 1, 2, 'fish', 600) (1, 2, 'fish', 600, 'eggs', 6)
>>> st.eggs=600 # raises TypeError like a normal tuple
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "SuperTuple.py", line 92, in __setattr__
    raise TypeError, "object doesn't support item assignment"
TypeError: object doesn't support item assignment
>>> for value in st:
...         print value
... 
1
2
fish
600
>>>

##The source begins...


from types import IntType

class SuperTuple:
	def __init__(self, *args, **kwargs):
		self.__named={}
		for name, value in kwargs.items():
			self.__named[name]=value
		self.__values=args+tuple(self.__named.values())
			
	def __getattr__(self, name):
		try:
			return self.__named[name]
		except KeyError, which:
			raise AttributeError, which
			
	def __getitem__(self, index):
		if type(index)!=IntType:
			return self.__named[index]
		else:
			return self.__values[index]
	
	def __setattr__(self, name, value):
		if name in ("_SuperTuple__values", "_SuperTuple__named"):
			self.__dict__[name]=value
		else:
			raise TypeError, "object doesn't support item assignment"

	def __repr__(self):
		return str(self.__values)
	
	def __add__(self, right):
		return self.__values+right

	def __radd__(self, left):
		return left+self.__values
	
	def names(self):
		return self.__named.keys()

## EOF SuperTuple.py

--
______________________________________________________________
|O| ----------------------------------------------------------
| | |Twisted mind? No, just bent in several strategic places.|
`\| |___________________________________mickut at iki.fi/mickut/|



More information about the Python-list mailing list