I'd like to subclass dict to disallow overwriting of keys, something like: class SafeDict(dict):
.... def __setitem__(self, key, value):
.... if key in self:
.... raise KeyError('cannot assign value %r to key %r, value %r'
.... 'already exists' % (value, key, self[key]))
.... super(SafeDict, self).__setitem__(key, value)
....
The problem is, dict doesn't appear to call __setitem__ in any of the
__init__ forms, so none of the following raise errors as I'd like them
to:
SafeDict({'one':1}, one=2)
{'one': 2} SafeDict([('one', 1), ('one', 2)])
{'one': 2} SafeDict([('one', 1), ('one', 2)], one=3)
{'one': 3} SafeDict(('one', x) for x in (1, 2))
{'one': 2}
etc. Is there a simple way to override this behavior in dict without
having to rewrite __init__? There are so many cases in dict.__init__
that I'm hesitant to try to reproduce them all...
Steve
--
You can wordify anything if you just verb it.
- Bucky Katt, Get Fuzzy 4 1327
Steven Bethard wrote: I'd like to subclass dict to disallow overwriting of keys, something like:
<snip>
The problem is, dict doesn't appear to call __setitem__ in any of the __init__ forms, so none of the following raise errors as I'd like them to:
<snap>
etc. Is there a simple way to override this behavior in dict without having to rewrite __init__? There are so many cases in dict.__init__ that I'm hesitant to try to reproduce them all...
How about starting with UserDict (source comes with your python
distribution) and modifying it for your needs?
Mathias
Mathias Waack wrote: Steven Bethard wrote:
I'd like to subclass dict to disallow overwriting of keys, something like:
<snip>
The problem is, dict doesn't appear to call __setitem__ in any of the __init__ forms, so none of the following raise errors as I'd like them to:
<snap>
etc. Is there a simple way to override this behavior in dict without having to rewrite __init__? There are so many cases in dict.__init__ that I'm hesitant to try to reproduce them all...
How about starting with UserDict (source comes with your python distribution) and modifying it for your needs?
Well, here's one reason I can think of: from UserDict import UserDict issubclass(UserDict, object)
0 issubclass(dict, object)
1 d = UserDict() type(d)
<type 'instance'>
UserDict is an old-style class. Simply converting it to use object as a
metaclass won't get you anywhere near the speed of a true dict.
regards
Steve
-- http://www.holdenweb.com http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119
Mathias Waack <M.Waack <at> gmx.de> writes: How about starting with UserDict (source comes with your python distribution) and modifying it for your needs?
I'm trying to avoid a huge code bloat for something that should be relatively
simple. Modifying and using UserDict would give me some 60+ lines of code to do
something I would hope could be done in much less. A somewhat better option
might be to copy/paste and slightly modify the __init__ and update code from
UserDict which do more or less what I want... But of course, this has the
problem of any copy/paste solution -- it will inevitably turn into a pain to
sync. What happens if dict acquires a new keyword argument? I have to update
my class again...
The code is not hard to write, but it *is* already written for the dict object.
If there's any way to take advantage of that fact, I'd like to.
Steve
Steven Bethard wrote: simple. Modifying and using UserDict would give me some 60+ lines of code
Not tested beyond what you see: import UserDict as userdict class Dict(userdict.DictMixin, dict):
.... def __setitem__(self, key, value):
.... if key in self: raise ValueError("key already exists")
.... super(Dict, self).__setitem__(key, value)
.... def __init__(self, other=None, **kw):
.... super(Dict, self).__init__()
.... self.update(other, **kw)
.... d = Dict({"one": 1}, one=2)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 7, in __init__
File "UserDict.py", line 155, in update
self.update(kwargs)
File "UserDict.py", line 147, in update
self[k] = v
File "<stdin>", line 3, in __setitem__
ValueError: key already exists d["one"] = 3
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in __setitem__
ValueError: key already exists
Peter This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Robin Cull |
last post by:
Imagine I have a dict looking something like this:
myDict = {"key 1": , "key
2": , "key 3": ,
"key 4": }
That is, a set of keys which have a variable length list of associated
values after...
|
by: GrelEns |
last post by:
hello,
i would like if this behaviour can be obtained from python : trap an
attributeError from inside a subclassing dict class... (here is a silly
examples to explain my question)
class...
|
by: Pierre Fortin |
last post by:
Hi,
Is the following a reasonable generic approach for converting python
returned tuples/lists into dicts...? I'm not advocating library functions
also return dicts (I'd probably spend more...
|
by: Alexander Kervero |
last post by:
Hi ,today i was reading diveinto python book,in chapter 5 it has a very
generic module to get file information,html,mp3s ,etc.
The code of the example is here :...
|
by: Kamilche |
last post by:
Hi everyone. I'm trying to convert a string that looks like this:
gid = 'FPS', type = 'Label', pos = , text = 'FPS', text2 = 'more
text without quotes', fmtline = "@VALUE @SIGNAL", signals =
...
|
by: Ilias Lazaridis |
last post by:
I understand that I can use __metaclass__ to create a class which
modifies the behaviour of another class.
How can I add this metaclass to *all* classes in the system?
(In ruby I would alter...
|
by: james_027 |
last post by:
hi,
a_dict = {'name':'apple', 'color':'red', 'texture':'smooth',
'shape':'sphere'}
is there any difference between ..
for key in a_dict:
from
|
by: mrkafk |
last post by:
Hello everyone,
I have written this small utility function for transforming legacy
file to Python dict:
def lookupdmo(domain):
lines = open('/etc/virtual/domainowners','r').readlines()...
|
by: Seongsu Lee |
last post by:
Hi,
I have a dictionary with million keys. Each value in the
dictionary has a list with up to thousand integers.
Follow is a simple example with 5 keys.
dict = {1: ,
2: ,
900000: ,
900001:...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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,...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
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...
|
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,...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
| |