[Tutor] List mimicing

Andrew Wilkins toodles@yifan.net
Wed, 6 Jun 2001 22:18:14 +0800


Hi folks,

I'm creating a class somewhat like shelve that stores a list as a file, and
provides a very list-like interface to it. I'm having troubles with __iadd__
and __imul__ however. When I call them, it deletes everything in my
file...if someone has enough time to go through my code, I would be _very_
appreciative. I'll delete the irrelevant parts to make it quicker/easier

Here's what i did to test __iadd__, __imul__ reacts the same way:

>>> import file
>>> x=file.ListShelf('a')
>>> x.get()
>>> x+=[1,2,3]
>>> x.get()
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in ?
    x.get()
AttributeError: 'None' object has no attribute 'get'
>>> print x
None

Thanks, Andrew

-------- code ----------

import cPickle,types,os

class ListShelf:
	def __init__(self,filename):
		"""
		Open file for updating if it exists, otherwise create it.
		"""
		if not os.access(filename,os.F_OK):
			os.open(filename,os.O_CREAT)
		self.file=open(filename,'r+')
	def get(self):
		return self._load()
	def _dump(self,_list):
		"""
		Seek to the beginning of file and cPickle the list to it.
		"""
		self.file.seek(0)
		cPickle.dump(_list,self.file)
	def _load(self):
		"""
		Seek to the beginning of file and un-cPickle the list from it.
		If the file is empty, return an empty list.
		"""
		self.file.seek(0)
		try:
			return cPickle.load(self.file)
		except EOFError: return []
	def __iadd__(self,other):
		"ie. list+=other"
		_list=self._load()
		_list+=other
		self._dump(_list)
	def __imul__(self,other):
		"ie. list*=other"
		_list=self._load()
		_list*=other
		self._dump(_list)