473,795 Members | 2,980 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dictionary inheritance

I want to make a dictionary that acts like a class, in other words,
supports inheritance: If you attempt to find a key that isn't present,
it searches a "base" dictionary, which in turn searches its base, and so on.

Now, I realize its fairly trivial to code something like this using
UserDict, but given that classes and modules already have this behavior,
is there some built-in type that already does this?

(This is for doing nested symbol tables and such.)

---

Also, on a completely different subject: Has there been much discussion
about extending the use of the 'is' keyword to do type comparisons a la
C# (e.g. "if x is list:") ?

-- Talin

Aug 12 '05 #1
6 1837
Talin wrote:
I want to make a dictionary that acts like a class, in other words,
supports inheritance: If you attempt to find a key that isn't present,
it searches a "base" dictionary, which in turn searches its base, and so on.

Now, I realize its fairly trivial to code something like this using
UserDict, but given that classes and modules already have this behavior,
is there some built-in type that already does this?

(This is for doing nested symbol tables and such.)

---

Also, on a completely different subject: Has there been much discussion
about extending the use of the 'is' keyword to do type comparisons a la
C# (e.g. "if x is list:") ?

-- Talin


Dictionaries aren't classes? I wasn't aware of that. Anyways, what
you're looking for, I think is a class that emulates a dictionary.
Probably you should just have some attribute that references a bigger
dictionary.

bigger_dict =
{'foo':1,'baz': 2,'bar':3,'foob ar':4,'foobaz': 5,'foobazbar':6 }
smaller_dict = {'spam':1,'ham' :2,'bacon':3,'e ggs':4}
smaller_dict.fa llback = bigger_dict

and then the __getitem__ method might look something like

def __getitem__(sel f, key):
if self.has_key(ke y):
return self[key]
else:
return self.fallback[key]

Aug 12 '05 #2
[Talin]
I want to make a dictionary that acts like a class, in other words,
supports inheritance: If you attempt to find a key that isn't present,
it searches a "base" dictionary, which in turn searches its base, and so on.


Perhaps the chainmap() recipe will meet your needs:

http://aspn.activestate.com/ASPN/Coo.../Recipe/305268
Raymond

Aug 13 '05 #3
Talin asked:
Also, on a completely different subject: Has there been much discussion
about extending the use of the 'is' keyword to do type comparisons a la
C# (e.g. "if x is list:") ?

-- Talin


No, is already has a specific, well defined meaning - object identity.

IDLE 1.1
a = [1,2,3]
a is list False b = type(a)
b <type 'list'> b is list True

"Extending it" to mean something entirely different to what it
currently means is a bad idea, and is also unnessecary - the builtin
function isinstance already provides the functionaliy you're looking
for:
isinstance(b, list) False isinstance(a, list) True


However, use sparingly - calling isinstance unnessecarily rather than
relying on polymorphism is considered pretty unpythonic, and usually
reflects pretty poor OO design.

Aug 13 '05 #4
Devan L wrote:
Talin wrote:
I want to make a dictionary that acts like a class, in other words,
supports inheritance:
(snip)
Dictionaries aren't classes?


They are.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Aug 13 '05 #5
Talin wrote:
I want to make a dictionary that acts like a class, in other words,
supports inheritance:
I must be missing your point here, since dict is a class and as such
support inheritence:
class MyDict(dict):pa ss .... d = MyDict()
d.items() []


If you attempt to find a key that isn't present,
it searches a "base" dictionary, which in turn searches its base, and so
on.
That's not inheritence, that's contextual acquisition (Zope relies
heavily on this concept).
Now, I realize its fairly trivial to code something like this using
UserDict,
If you want to specialize dict, why use UserDict ?
but given that classes and modules already have this behavior,
Nope. Inheritence is not the solution - unless of course you want to
create a derived class for each and any of your 'nested dict' instances,
which would be a rather strange design...
Here you need composition/delegation:

class HierDict(dict):
def __init__(self, parent=None):
self._parent = parent

def __getitem__(sel f, name):
try:
return super(HierDict, self).__getitem __(name)
except KeyError, e:
if self._parent is None:
raise
return self._parent[name]

# to be continued according to your needs
if __name__ == "__main__":
d = HierDict(None)
d['test'] = 42
print d['test']

d2 = HierDict(d)
d2['dead'] = "parrot"

print d2['dead'] # found in d2
print d2['test'] # found in d


Also, on a completely different subject: Has there been much discussion
about extending the use of the 'is' keyword to do type comparisons a la
C# (e.g. "if x is list:") ?


I don't think there is much to discuss:

x = list
if x is list:
print "x is list"

Remember that in Python,
1/ type information pertains to objects, not to identifiers
2/ types are objects too

So, the 'is' operator being the identity operator, there is no need to
'extend' it to do type comparisons:

x = []
if type(x) is type([]):
print "x is a list"

But - even if useful in some special cases -, type comparisons in
Python are rarely necessary and in most case worst than useless:

def get_foo(a_dict) :
if type(a_dict) is type({}):
foo = a_dict['foo']
else:
raise TypeError, "expected a dict, got something else"

h = HierDict()
h['foo'] = 'bar'

get_foo(h)
....definitivel y worst than useless...

-
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Aug 13 '05 #6
On Fri, 12 Aug 2005 12:44:11 -0700, Talin wrote:
I want to make a dictionary that acts like a class, in other words,
supports inheritance: If you attempt to find a key that isn't present,
it searches a "base" dictionary, which in turn searches its base, and so on.

Now, I realize its fairly trivial to code something like this using
UserDict, but given that classes and modules already have this behavior,
is there some built-in type that already does this?

(This is for doing nested symbol tables and such.)

---


You could always do:

class nestedDict(dict ):
...
Aug 13 '05 #7

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

Similar topics

1
3592
by: none | last post by:
or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148 respectively In the sample code you see that I have class Item and class Dict class Dict contains a dictionary called items. The items dictionary will contain instances of Item that are keyed off of the Item name. In __main__ I create two...
11
18711
by: Pavils Jurjans | last post by:
Hello, There's some confusion about the purpose and difference between these handy classes... First, both of them are holding number of key - value pairs, right? Then, I see that there may be some difference in terms of data types allowed for keys and values, perhaps? I read the following in MSDN about "CollectionBase" class and
1
9263
by: john wright | last post by:
I have a dictionary oject I created and I want to bind a listbox to it. I am including the code for the dictionary object. Here is the error I am getting: "System.Exception: Complex DataBinding accepts as a data source either an IList or an IListSource at System.Windows.Forms.ListControl.set_DataSource(Object value)
90
10827
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in future Python versions and let dict.keys() and dict.values() both return sets instead of lists. If d is a dict, code like: for x in d.keys():
8
17840
by: Brian P | last post by:
I want to expose a property of Dictionary<string, MyAbstractClass>. I tried to do it this way: private Dictionary<string, MyChildClass> _dictionary; public Dictionary<string, MyAbstractClass> { get { return _dictionary; } //error: no implicit conversion. }
1
1441
by: Steve Long | last post by:
Hello, I'm trying to expose a string dictionary to a COM client (VB6) and I'm having some trouble with the Keys property of the StringDictionary. My class is laid out as such: The problem is that when I hit the Keys property VB6 says that the object doesn support the method or property. Help??? <ClassInterface(ClassInterfaceType.AutoDual), Guid("F04A8EDA-C857-4dec-BFCA-A41744CAB48B")> _ Public Class Dictionary
5
13321
by: mmurrell | last post by:
I have a generic dictionary (lets call ChildCollection). I would like to ensure that whenever a child is added to this collection (SomeParent.Children.Add(new Child()), the parent of the child object is set appropriately. For some reason I would like to understand, the Add method of System.Collections.Generic.Dictionary<Tkey, TValis not virtual. Can anyone offer some advice on how to accomplish this. I would like to avoid...
1
1758
by: John Grandy | last post by:
What is the correct syntax for the following : Public Class EnumList<T: Dictionary<int, T> { } Or is this even possible ?
7
79265
by: Guillermo | last post by:
Hello, This is my first post here. I'm getting my feet wet with Python and I need to know how can I check whether a variable is of type dictionary. Something like this: if isdict(a) then print "a is a dictionary" Regards,
0
9522
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
10448
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
10217
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10167
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10003
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
6784
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5566
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4114
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
2
3730
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.