Python 2.2, creating new types from base types

Peter Milliken peter.milliken at gtech.com
Thu Jan 17 17:01:30 EST 2002


I would like to create a specialised data type that is essentially a
dictionary of dictionaries (I want to do some algorithmic "fiddling" with
the second key of the data structure i.e. if the second key doesn't match
exactly then search for the closest match for that data). The structure is
like this:

  { x : { y : { z : value}}}

My first thoughts were to use Python 2.2 "special new features" to subclass
the dict type like this, thereby creating a new data type:


class my_dict (dict):

  def __init__ (self):
      self.special_dict = {'1' : {'2' : {'3' : '4'}}}    # Example data to
"try" it all out


Accessing the contents of an instance should (to my way of thinking :-)) be
something like this:

abc = my_dict()

print abc['1']['2']['3']


Now, I wasn't sure how to overload the __getitem__ def but thought it might
be achievable using **args or something like that, I have played around with
several combinations of __getitem__ but can't quite work out how to get this
working. I have used the following without success:


  def __getitem__ (self, key):
     .....

  def __getitem__ (self, **keys):
    .....

I must be doing something fundamentally wrong here, could someone please
point out the obvious for me? :-) It seems like it should work, but
doesn't..... Certainly being able to subclass dict to come up with a
specialised form of dict should be achievable using the new features.


Thanks
Peter





More information about the Python-list mailing list