UserDict's has_key() and get() should use __getitem__()

Michael Hudson mwh21 at cam.ac.uk
Wed Apr 5 07:36:19 EDT 2000


Hamish Lawson <hamish_lawson at yahoo.co.uk> writes:

> However, under the current implementation of UserDict, if you
> redefine __getitem__() in your own UserDict-derived class, you
> will probably also have to redefine has_key() and get() (and
> maybe others) in order to have them behave as expected. This
> wholescale redefining is caused by the fact that UserDict's
> has_key() and get() methods don't make use of the class's own
> __getitem__() method in determining whether a key exists, as
> shown in the extract below:
> 
>     def __getitem__(self, key):
>         return self.data[key]
>     def has_key(self, key):
>         return self.data.has_key(key)
>     def get(self, key, failobj=None):
>         return self.data.get(key, failobj)
> 
> My contention is that the behaviour we expect from get() and
> has_key() is intimately bound up with how __getitem__() behaves,
> and this should be reflected in get() and has_key() making use
> of __getitem__():
> 
>     def has_key(self, key):
>         try:
>             self[key]
>             return 1
>         except KeyError:
>             return 0
>     def get(self, key, failobj=None):
>         try:
>             return self[key]
>         except KeyError:
>             return failobj

Hmm.  These are likely to be rather less efficient than the current
implementation, so you want to penalise those who use UserDict for the
sake of those who don't subclass it thoroughly - do you really want to
do this?  Let's face it, you're unlikely to make this mistake again.

Cheers,
M.

-- 
well, take it from an old hand: the only reason it would be easier
to program in C is that you can't easily express complex  problems
in C, so you don't.                 -- Erik Naggum, comp.lang.lisp



More information about the Python-list mailing list