473,405 Members | 2,421 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Help and optimization hints, anyone?

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?

Also optimization hints and alternatives will be greatly appreciated.

<code>
#!env python
#
# created: "15:19 20/01-2004" by Kim Petersen <ki*@vindinggaard.dk>
#
# $Id$
#
import Tkinter

class UserDict:
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:
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)

class Cell(UserDict):
defaults={"width": 0,"height": 0,"text": '',"color": "black","background": "white",
"widgets": None}
def __init__(self,master,row,column,text):
UserDict.__init__(self,[row,column])
self.master=master
self["text"]=text
self.row=row # these are needed for us to find the actual row/col
self.column=column
self.create()

def create(self):
"""Create the widgets the first time (might inflict up to two resize's)"""
x,y=self.column["x"],self.row["y"]
w,h=self.column["width"],self.row["height"]
r=self.master.create_rectangle((x,y,x+w,y+h),fill= self["background"])
t=self.master.create_text((x+self.master.colpaddin g,y+h/2),
text=self["text"],
anchor="w",fill=self["color"])
self["widgets"]=[r,t]
bbox=self.master.bbox(t)
self["width"]=bbox[2]-bbox[0]
self["height"]=bbox[3]-bbox[1]
if self["width"]+self.master.colpadding*2>w:
self.column.resize(self["width"]+self.master.colpadding*2)
self.resize()
if self["height"]+self.master.rowpadding*2>h:
self.row.resize(self["height"]+self.master.rowpadding*2)
self.resize()

def resize(self):
"""Resize according to the width/height given by row,column"""
x,y=self.column["x"],self.row["y"]
w,h=self.column["width"],self.row["height"]
self.master.coords(self["widgets"][0],(x,y,x+w,y+h))
self.master.coords(self["widgets"][1],(x+self.master.colpadding,y+h/2))

def move(self,dx,dy):
"""Relatively move according to delta's"""
self.master.move(self["widgets"][0],dx,dy)
self.master.move(self["widgets"][1],dx,dy)

class Column(UserDict):
""" """
defaults={"x": 0,"width": 0,"label": '',"tag": ''}

def __init__(self,master,label='',before=None):
UserDict.__init__(self)
self.master=master
if master.columns:
if not before or before>0:
if not before:
after=(-1)
else:
after=before-1
self.dict["x"]=master.columns[after]["x"]+master.columns[after]["width"]
# since we have a width of 0 there is no need to move the rest of the columns.

def calcwidth(self):
"""Calculate the *actually* needed width of the column (*not* the current one)."""
width=0
for row in self.master.rows:
width=max(self.master.cells[(row,self)]["width"],width)
return width+self.master.colpadding*2

def resize(self,width):
# calc delta, set new width
dx=width-self["width"]
self["width"]=width
ci=self.master.columns.index(self)
# resize the cells
for row in self.master.rows:
try:
self.master.cells[(row,self)].resize()
except KeyError:
pass
# move columns to the right further to the right
for i in range(ci+1,len(self.master.columns)):
self.master.columns[i].move(dx)

def move(self,dx):
self["x"]=self["x"]+dx
# move the cells correspondingly
for row in self.master.rows:
try:
self.master.cells[(row,self)].move(dx,0)
except KeyError:
pass

class Row(UserDict):
defaults={"y": 0,"height": 0,"label": '',"tag": ''}
def __init__(self,master,label,before=None):
UserDict.__init__(self)
self["label"]=label
# now insert it.
self.master=master
if master.rows:
if not before or before>0:
if not before:
after=(-1)
else:
after=before-1
self.dict["y"]=master.rows[after]["y"]+master.rows[after]["height"]

def calcheight(self):
"""Calculate the *actually* needed width of the column (*not* the current one)."""
height=0
for row in self.master.columns:
height=max(self.master.cells[(self,column)]["height"],height)
return height+self.master.rowpadding*2

def resize(self,height):
dy=height-self.dict["height"]
self.dict["height"]=height
ri=self.master.rows.index(self)
for column in self.master.columns:
if self.master.cells.has_key((self,column)):
self.master.cells[(self,column)].resize()
for i in range(ri+1,len(self.master.rows)):
self.master.rows[i].move(dy)

def move(self,dy):
self.dict["y"]=self.dict["y"]+dy
for col in self.master.columns:
try:
self.master.cells[(self,col)].move(0,dy)
except KeyError:
pass
pass

def moveto(self,y):
self.move(y-self.dict["y"])

def __setitem__(self,name,value):
if name=="height":
self.resize(value)
elif name=="y":
self.move(value-self["y"])
else:
self.dict[name]=value

class Table(Tkinter.Canvas):
"""A table object - it consists of a number of cells layed out in rows and columns

A row has a specific height
A row can have a label
A column has a specific width
A column can have a label
"""

def __init__(self,master,**args):
Tkinter.Canvas.__init__(self,master,**args)
self.colpadding=2
self.rowpadding=2
self.columns=[] # each item contains data about the column
self.rows=[] # each item contains data about the row
self.cells={} # index: (row,col)

def insertrow(self,pos,values):
self.rows[pos:pos]=[Row(self,'',pos)]
row=self.rows[pos]
for i in range(len(values)):
if i<len(self.columns):
col=self.columns[i]
else:
self.columns.append(Column(self,''))
col=self.columns[-1]
self.cells[(row,col)]=Cell(self,row,col,values[i])

def row_add(self,values):
self.rows.append(Row(self,''))
row=self.rows[-1]
for i in range(len(values)):
if i<len(self.columns):
col=self.columns[i]
else:
self.columns.append(Column(self,''))
col=self.columns[-1]
self.cells[(row,col)]=Cell(self,row,col,values[i])

if __name__=="__main__":
tk=Tkinter.Tk()
tk.grid_rowconfigure(1,weight=1)
tk.grid_columnconfigure(1,weight=1)
tk.wm_geometry("800x1150+0+0")

table=Table(tk)
table.grid(row=1,column=1,sticky="nsew")
for line in open("/etc/passwd","r"):
values=unicode(line.strip(),"iso8859-1").split(":")
#tk.update()
#table.insertrow(0,values)
table.row_add(values)
for row in table.rows:
print row["y"],row["height"]
tk.mainloop()

# Local Variables:
# tab-width: 3
# py-indent-offset: 3
# End:
</code>
--
Privat ========================== Kim Petersen ==================== Arbejde
Email ki*@vindinggaard.dk ===== Jens Grøns Vej 11 ===== Email ki*@lignus.dk
Tlf +45 75 83 15 50 ============== 7100 Vejle ========= Tlf +45 75 83 15 51
Fax +45 75 83 15 62 ============= DK - Danmark ======== Fax +45 75 83 15 62
Jul 18 '05 #1
4 1584
Kim Petersen <ki*@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 <ki*@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
Jul 18 '05 #2
Den Fri, 23 Jan 2004 12:32:04 +0000. skrev John J. Lee:
Kim Petersen <ki*@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.


thx. no problem tho - i should've remembered.

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.


Actually i was planning to use the standard UserDict
(basically because a class is hashable and dict isn't) - i
got carried away and put some default handling in it as well - but
didn't rename ;-)

dict is also a bad name -- this is the name of the builtin dictionary
type, which you've just clobbered (in the local scope).
Hmmm - isn't it called __dict__ ?

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().


yup - oversight
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).


this migrated from a regular dict which i had to drop because its
not hashable as mentioned earlier - next step __(get|set)attr__.

John


--
Privat ========================== Kim Petersen ==================== Arbejde
Email ki*@vindinggaard.dk ===== Jens Grøns Vej 11 ===== Email ki*@lignus.dk
Tlf +45 75 83 15 50 ============== 7100 Vejle ========= Tlf +45 75 83 15 51
Fax +45 75 83 15 62 ============= DK - Danmark ======== Fax +45 75 83 15 62

Jul 18 '05 #3
Kim Petersen <ki*@lignus.dk> writes:
Den Fri, 23 Jan 2004 12:32:04 +0000. skrev John J. Lee:

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


Hmmm - isn't it called __dict__ ?


No, __dict__ is an attribute of Python objects. It's the dictionary
in which most Python objects keep their data:
class foo: .... def __init__(self):
.... self.blah = "stuff"
.... f = foo()
f.__dict__ {'blah': 'stuff'}
dict is the builtin name for the dictionary type:
dict <type 'dict'> dict({"foo": "bar", "spam": "eggs"}) {'foo': 'bar', 'spam': 'eggs'} dict([("foo", "bar"), ("spam", "eggs")])
{'foo': 'bar', 'spam': 'eggs'}

[...] 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).


this migrated from a regular dict which i had to drop because its
not hashable as mentioned earlier - next step __(get|set)attr__.


dicts are deliberately not hashable, because they're mutable. Are you
sure you want a dict as a dictionary key (assuming that's what you're
doing)?
John
Jul 18 '05 #4
Den Fri, 23 Jan 2004 16:20:37 +0000. skrev John J. Lee:
Kim Petersen <ki*@lignus.dk> writes:
Den Fri, 23 Jan 2004 12:32:04 +0000. skrev John J. Lee: [...]
> dict is also a bad name -- this is the name of the builtin dictionary
> type, which you've just clobbered (in the local scope).


Hmmm - isn't it called __dict__ ?


No, __dict__ is an attribute of Python objects. It's the dictionary
in which most Python objects keep their data:


ah - the class dict() - yeah i can see that (i didn't notice since
i hardly ever call dict() directly but do it indirectly via {}. Sure
i've clobbered that internally in this class and derived (will change)
> 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).


this migrated from a regular dict which i had to drop because its
not hashable as mentioned earlier - next step __(get|set)attr__.


dicts are deliberately not hashable, because they're mutable. Are you
sure you want a dict as a dictionary key (assuming that's what you're
doing)?


I had the columns,rows and cells as simply dicts in the beginning,
but that made self.cells[(row,column)] impossible - so i converted
to classes instead (which works just as well). And migrated func-
tionality to the classes. [this is also the reason for the attributes
being access as dict].

John


--
Privat ========================== Kim Petersen ==================== Arbejde
Email ki*@vindinggaard.dk ===== Jens Grøns Vej 11 ===== Email ki*@lignus.dk
Tlf +45 75 83 15 50 ============== 7100 Vejle ========= Tlf +45 75 83 15 51
Fax +45 75 83 15 62 ============= DK - Danmark ======== Fax +45 75 83 15 62

Jul 18 '05 #5

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

Similar topics

8
by: | last post by:
I would like to optimize my classes at run time. The question is where to put my "if" statement. -Inside __main__? if option: class Foo: def __init__: #do stuff else: class Foo: def __init__:
16
by: JustSomeGuy | last post by:
I have a routine that evaluates a polynomial equation that have 3 variables x,y,z of orders 1,2,3 the coefficients of the polynomial are in an array. This routine is quite slow and I'd like to...
3
by: Nick L. | last post by:
All, This is a general question regarding how, and if, compiler optimization techniques affect the general concept of being able to update a component of an application without requiring a...
31
by: mark | last post by:
Hello- i am trying to make the function addbitwise more efficient. the code below takes an array of binary numbers (of size 5) and performs bitwise addition. it looks ugly and it is not elegant...
11
by: syed | last post by:
I want clues to optimize a function that copies elements of a 2-dimensional array to another. Is there a way to optimize this piece of code so that it runs faster? #define RIDX(i,j,n)...
1
by: amcnpr33 | last post by:
Please forward this or reply to beth@laurus-group.com MySQL DBA/Architect - An innovator in the Internet Search Marketing industry is looking for talented, fun team members. MySQL DBA/Architect...
2
by: dp_pearce | last post by:
I have some code that takes data from an Access database and processes it into text files for another application. At the moment, I am using a number of loops that are pretty slow. I am not a...
20
by: Ravikiran | last post by:
Hi Friends, I wanted know about whatt is ment by zero optimization and sign optimization and its differences.... Thank you...
8
by: iPaul | last post by:
hi this is my code #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdlib.h> #include <string.h> #include <iostream>
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.