473,763 Members | 9,275 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

new style shelve implementation

I'm using the shelve module for a program I'm writing, and reading the
source I've noted that shelve doesn't use new style classes.
Well, this is the first time I use *seriously* new style classes (I work
primarly on Zope and Python 2.1), so the result is probably far from
production code, but after half an hour of hacking my Shelf class seems to
work like the original one (much more than what I expected...) :)

class Shelf (dict):

def __init__ (self, dict, protocol = None, writeback = False, binary = None):
self.dict = dict
if protocol is not None and binary is not None:
raise ValueError, "can't specifiy both 'protocol' and 'binary'"
if binary is not None:
warnings.warn ("The 'binary' argument to Shelf() is deprecated",
PendingDeprecat ionWarning)
protocol = int (binary)
if protocol is None:
protocol = 0
self.protocol = protocol
self.writeback = writeback
self.cache = {}

def __repr__ (self):
dummy = dict ()
for k in self.keys ():
dummy [k] = self [k]
return repr (dummy)

def keys (self):
return self.dict.keys ()

def __len__ (self):
return len (self)

def has_key (self, key):
return self.dict.has_k ey (key)

def __contains__ (self, key):
return self.has_key (key)

def get (self, key, default = None):
if self.has_key (key):
return self.dict [key]
return default

def __getitem__ (self, key):
try:
value = self.cache [key]
except KeyError:
f = StringIO (self.dict [key])
value = Unpickler (f).load ()
if self.writeback:
self.cache [key] = value
return value

def __setitem__ (self, key, value):
if self.writeback:
self.cache [key] = value
f = StringIO ()
p = Pickler (f, self.protocol)
p.dump (value)
self.dict [key] = f.getvalue ()

def __delitem__ (self, key):
del self.dict [key]
try:
del self.cache [key]
except KeyError:
pass

def close (self):
self.sync ()
try:
self.dict.close ()
except AttributeError:
pass
self = None

def __del__ (self):
self.close ()

def sync (self):
if self.writeback and self.cache:
self.writeback = False
for key, entry in self.cache.iter items ():
self.dict [key] = entry
self.writeback = True
self.cache = {}
if hasattr (self.dict, "sync"):
self.sync ()

Everything else is like the original one, I've just added a totally
unpythonic implementation of the __repr__ method and removed the UserDict
dependency.
IMVHO if UserDict is going to be removed it's good to start removing
it from the python library.
On the other hand, this is just a dirty hack, so every comment is deeply
appreciated.

Happy new year,
nicholas
Jul 18 '05 #1
0 1068

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
4755
by: Rami A. Kishek | last post by:
Hi - this mysterious behavior with shelve is just about to kill me. I hope someone here can shed some light. First of all, I have this piece of code which uses shelve to save instances of some class I define. It works perfectly on an old machine (PII-400) running Python 2.2.1 under RedHat Linux 8.0. When I try to run it under Python for windows ME on a P-4 1.4 GHz, however, it keeps crashing on reading from the shelved file the second...
1
6746
by: Kris Caselden | last post by:
Python's docs say that Shelve uses Pickle to serialize its data. However, I've noticed that Pickle can maintain internal links, while Shelve cannot. For instance: >>> d = shelve.open('shelvedata.txt',writeback=True) >>> d= >>> d=d >>> print d {'a': , 'b': } >>> d=2 >>> print d {'a': , 'b': }
0
2472
by: seth | last post by:
Last week I encountered an AttributeError in my unit tests that I wasn'table to catch with an "except AttributeError" statement. The problem stemmed from a class that raised an error inside __init__and defined a __del__ method to clean up resources. I then discovered asimilar problem in the shelve module. This led me to two importantdiscoveries: 1. Attributes defined in __init__ after an error is raised will not be apart of the...
0
2034
by: ex laguna | last post by:
Hi, I have ran into a problem with py2exe 0.5.0 and shelve in python 2.3.3. The script works fine standalone, but not with py2exe. Does anyone have a solution of workaround for this? Thanks much. # Begin of setup.py from distutils.core import setup import py2exe setup(console=)
0
1371
by: Ray O | last post by:
I have read a number of threads relating to problems with shelve, but I couldn't find one directly related my experience, so I would appreciate some advice. The closest one ended with a recommendation to upgrade to Python 2.3, but that, unfortunately, is out of my control. The system I use runs Python 2.2.2, and whichdb gives dbhash. The problem only occurs when serializing class instances; lists don't seem to be affected. Every time...
3
7888
by: Michele Petrazzo | last post by:
Hi, I'm trying a script on a debian 3.1 that has problems on shelve library. The same script work well on a fedora 2 and I don't know why it create this problem on debian: #extract from my code import shelve class XX: def __init__(self): self._data = shelve.open("/tmp/myfile")
13
6515
by: 7stud | last post by:
test1.py: -------------------- import shelve s = shelve.open("/Users/me/2testing/dir1/aaa.txt") s = "red" s.close() --------output:------ $ python test1.py
5
1645
by: gluckj | last post by:
Hi, I'm not a Win ME fan myself (I'm a Mac user), but I'm here in Thailand developing software for special-needs kids, and the test PC in my home office is a Win ME machine (sigh). So when I ported my Python program today to the PC, it quickly crashed. Everything seems to work except for shelve. Using the latest version of Python (2.5.1), when I do the following in IDLE on the Win ME machine here's the result: Python 2.5.1...
1
4585
by: Matthew Schibler | last post by:
I'm a newbie to Python, with some experience using perl (where I used nested arrays and hashes extensively). I am building a script in python for a MUD I play, and I want to use the shelve module to store persistent information between script executions. The following code does not work for me, import shelve, sys, os, string db = shelve.open(os.path.abspath(os.path.dirname(sys.argv)) + '/' + 'sandbox.dat', 'c') db = 'apple'
0
9564
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9387
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10148
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9823
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2794
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.