Python 2.2, creating new types from base types

Joseph A Knapka jknapka at earthlink.net
Fri Jan 18 00:21:18 EST 2002


Peter Milliken wrote:
> 
> Hi Terry,
> 
> I think this would work but "violates" the concept I have in my
mind of
> subclassing a type

Why do you want it to be a type, particularly? I think you
can get exactly what you want by implementing a simpler
type that just implements __getitem__ to create empty
dictionaries when necessary (note: I don't have 2.2 yet):

>>> from UserDict import *
>>> class myDict(UserDict):
...   def __getitem__(self,item):
...     if item in self.data.keys():
...       return self.data[item]
...     self.data[item] = myDict({})
...     return self.data[item]
... 
>>> m = myDict()
>>> m['1']['2'] = 3
>>> m['1']['2']
3
>>> m['1']
{'2': 3}
>>> m2 = myDict()
>>> m2['1']['2']['3'] = 4
>>> m2['1']['2']['3']
4
>>> m2['1']
{'2': {'3': 4}}
>>> m2
{'1': {'2': {'3': 4}}}
>>> 

Yes?

Cheers,

-- Joe
"I should like to close this book by sticking out any part of my neck
 which is not yet exposed, and making a few predictions about how the
 problem of quantum gravity will in the end be solved."
 --- Physicist Lee Smolin, "Three Roads to Quantum Gravity"



More information about the Python-list mailing list