Help and optimization hints, anyone?

John J. Lee jjl at pobox.com
Fri Jan 23 07:32:04 EST 2004


Kim Petersen <kim at lignus.dk> writes:

> I've worked on this table object a bit too long - and seem to have
> stared too long at the code. Can someone see where it goes wrong in
> the insertrow function?

I made a few comments before I realised it was a Tkinter question, so
no answer, sorry!  Just some style hints.

BTW, it's very helpful to mention in the subject line when a
particular GUI toolkit is involved (or when any other large library is
a central part of the question, for that matter).


> Also optimization hints and alternatives will be greatly appreciated.
> 
> <code>
> #!env python
> #
> # created: "15:19 20/01-2004" by Kim Petersen <kim at vindinggaard.dk>
> #
> # $Id$
> #
> import Tkinter
> 
> class UserDict:

Bad name -- UserDict is a standard library module.  In 2.2 or newer,
you can subclass dict.  In 2.3, you also have the option of
subclassing UserDict.DictMixin.  If you just want to implement part of
the maping interface, just call your class something other than
UserDict -- say SimpleDefaultDictBase.


>    defaults={}
>    def __init__(self,inherit=None):
>       if not inherit:
>          self.inherit=[]
>       else:
>          self.inherit=inherit
>       self.dict=self.defaults.copy()
> 
>    def __setitem__(self,name,value): self.dict[name]=value
> 
>    def __getitem__(self,name):
>       if not self.dict.has_key(name):
>          for dict in self.inherit:

dict is also a bad name -- this is the name of the builtin dictionary
type, which you've just clobbered (in the local scope).


>             if dict.has_key(name):
>                return dict[name]
>          raise KeyError,"%s not found" % (name,)
>       return self.dict[name]
> 
>    def haskey(self,name): return self.dict.has_key(name)

Did you really mean to call it that?  The dict interface has a method
.has_key(), not .haskey().


> class Cell(UserDict):
>    defaults={"width": 0,"height": 0,"text": '',"color": "black","background": "white",
>             "widgets": None}
[...]

Haven't read much further, but it looks like you might be better off
using attribute access rather than indexing.  In 2.2, use properties.
Earlier, use __setattr__ / __getattr__ (make sure you read the docs).


John



More information about the Python-list mailing list