473,785 Members | 2,736 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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*@vindinggaa rd.dk>
#
# $Id$
#
import Tkinter

class UserDict:
defaults={}
def __init__(self,i nherit=None):
if not inherit:
self.inherit=[]
else:
self.inherit=in herit
self.dict=self. defaults.copy()

def __setitem__(sel f,name,value): self.dict[name]=value

def __getitem__(sel f,name):
if not self.dict.has_k ey(name):
for dict in self.inherit:
if dict.has_key(na me):
return dict[name]
raise KeyError,"%s not found" % (name,)
return self.dict[name]

def haskey(self,nam e): return self.dict.has_k ey(name)

class Cell(UserDict):
defaults={"widt h": 0,"height": 0,"text": '',"color": "black","backgr ound": "white",
"widgets": None}
def __init__(self,m aster,row,colum n,text):
UserDict.__init __(self,[row,column])
self.master=mas ter
self["text"]=text
self.row=row # these are needed for us to find the actual row/col
self.column=col umn
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.c reate_rectangle ((x,y,x+w,y+h), fill=self["background "])
t=self.master.c reate_text((x+s elf.master.colp adding,y+h/2),
text=self["text"],
anchor="w",fill =self["color"])
self["widgets"]=[r,t]
bbox=self.maste r.bbox(t)
self["width"]=bbox[2]-bbox[0]
self["height"]=bbox[3]-bbox[1]
if self["width"]+self.master.co lpadding*2>w:
self.column.res ize(self["width"]+self.master.co lpadding*2)
self.resize()
if self["height"]+self.master.ro wpadding*2>h:
self.row.resize (self["height"]+self.master.ro wpadding*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.coo rds(self["widgets"][0],(x,y,x+w,y+h))
self.master.coo rds(self["widgets"][1],(x+self.master .colpadding,y+h/2))

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

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

def __init__(self,m aster,label='', before=None):
UserDict.__init __(self)
self.master=mas ter
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) :
"""Calculat e the *actually* needed width of the column (*not* the current one)."""
width=0
for row in self.master.row s:
width=max(self. master.cells[(row,self)]["width"],width)
return width+self.mast er.colpadding*2

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

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

class Row(UserDict):
defaults={"y": 0,"height": 0,"label": '',"tag": ''}
def __init__(self,m aster,label,bef ore=None):
UserDict.__init __(self)
self["label"]=label
# now insert it.
self.master=mas ter
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 ):
"""Calculat e the *actually* needed width of the column (*not* the current one)."""
height=0
for row in self.master.col umns:
height=max(self .master.cells[(self,column)]["height"],height)
return height+self.mas ter.rowpadding* 2

def resize(self,hei ght):
dy=height-self.dict["height"]
self.dict["height"]=height
ri=self.master. rows.index(self )
for column in self.master.col umns:
if self.master.cel ls.has_key((sel f,column)):
self.master.cel ls[(self,column)].resize()
for i in range(ri+1,len( self.master.row s)):
self.master.row s[i].move(dy)

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

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

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

class Table(Tkinter.C anvas):
"""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,m aster,**args):
Tkinter.Canvas. __init__(self,m aster,**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(value s)):
if i<len(self.colu mns):
col=self.column s[i]
else:
self.columns.ap pend(Column(sel f,''))
col=self.column s[-1]
self.cells[(row,col)]=Cell(self,row, col,values[i])

def row_add(self,va lues):
self.rows.appen d(Row(self,''))
row=self.rows[-1]
for i in range(len(value s)):
if i<len(self.colu mns):
col=self.column s[i]
else:
self.columns.ap pend(Column(sel f,''))
col=self.column s[-1]
self.cells[(row,col)]=Cell(self,row, col,values[i])

if __name__=="__ma in__":
tk=Tkinter.Tk()
tk.grid_rowconf igure(1,weight= 1)
tk.grid_columnc onfigure(1,weig ht=1)
tk.wm_geometry( "800x1150+0 +0")

table=Table(tk)
table.grid(row= 1,column=1,stic ky="nsew")
for line in open("/etc/passwd","r"):
values=unicode( line.strip(),"i so8859-1").split(": ")
#tk.update()
#table.insertro w(0,values)
table.row_add(v alues)
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*@vindinggaar d.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 1602
Kim Petersen <ki*@lignus.d k> 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*@vindinggaa rd.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.DictMi xin. If you just want to implement part of
the maping interface, just call your class something other than
UserDict -- say SimpleDefaultDi ctBase.

defaults={}
def __init__(self,i nherit=None):
if not inherit:
self.inherit=[]
else:
self.inherit=in herit
self.dict=self. defaults.copy()

def __setitem__(sel f,name,value): self.dict[name]=value

def __getitem__(sel f,name):
if not self.dict.has_k ey(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(na me):
return dict[name]
raise KeyError,"%s not found" % (name,)
return self.dict[name]

def haskey(self,nam e): return self.dict.has_k ey(name)
Did you really mean to call it that? The dict interface has a method
..has_key(), not .haskey().

class Cell(UserDict):
defaults={"widt h": 0,"height": 0,"text": '',"color": "black","backgr ound": "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.d k> 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.DictMi xin. If you just want to implement part of
the maping interface, just call your class something other than
UserDict -- say SimpleDefaultDi ctBase.


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,nam e): return self.dict.has_k ey(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={"widt h": 0,"height": 0,"text": '',"color": "black","backgr ound": "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*@vindinggaar d.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.d k> 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.d k> 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*@vindinggaar d.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
1436
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
2277
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 optimize it. Any suggestions? simply put pts is a vector of typdef struct double x; double y; double z;
3
3315
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 recompile of client code. For example, suppose I have component: common.dll which defines several constant values, say Const_A, Const_B and Const_C. Further say I have some client code in another component: client.dll which references common.dll and...
31
2647
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 but it appears to work. using time, i measured it takes .041s to execute, which i admit isnt much. but, the problem is that this procedure will be called many, many times in my project (probably at least a few thousand times, if not more) so...
11
3008
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) ((i)*(n)+(j)) void myrotate(int dim, pixel *src, pixel *dst) {
1
1493
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 should have strong MySQL database design and optimization Open Source and Data warehouse/architect experience. This post is in R&D. Do you know anyone who would be interested in working for a stable profitable, fun start up? I worked with the...
2
201
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 hugely experienced python user so I would like to know if I am doing anything particularly wrong or that can be hugely improved through the use of another method. Currently, all of the values that are to be written to file are pulled from the...
20
2359
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
1905
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
9480
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10147
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10087
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8971
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7496
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6737
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2877
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.