Style Question

Dear Folks,

I have doubts about my coding style

            if (buttons&16):
                Dist=[]
                DistL=[]
                #KeyPos in Dictonary abspeichern
                # Wenn Entfernung des Neuen Punktes mindestens 20cm von einem Vorhandenen ist 
                # wird der Neue Punkt in den Dict aufgenommen
                for i in range(len(self.KeyPosDic.keys())):
                    Dist.append(self.PosVec-self.KeyPosDic.values()[i])
                    DistL.append(Dist[i].length())
                DistL.sort()
                if len(DistL)==0:
                    self.KeyPosDic['KeyPos '+str(len(self.KeyPosDic.items()))+' =']=self.PosVec
                elif DistL[0] >= 0.2:
                    self.KeyPosDic['KeyPos '+str(len(self.KeyPosDic.items()))+' =']=self.PosVec                   
                for i in range(len(self.KeyPosDic.keys())):
                    #print self.KeyPosDic
                    #KeyPositionModel
                    self.KeyPosM =loader.loadModel("models/BallSmall")
                    self.KeyPosM.setShaderInput("texDisable",1,1,1,1)
                    self.KeyPosM.setPos(self.PosVec)            
                    self.KeyPosM.reparentTo(self.environ)

This could be solved more elegantly but how?

cheers

Martin

  1. python.org/dev/peps/

  2. write comments in english if you want us all to understand them

  3. you iterate through the length of a dict, but in many cases this isn’t necessary. you can as well iterate through the dict itself (which is equavilent to dict.keys()) or use items(), iteritems(), iterkeys() or itervalues(). type help(dict) into the python shell and you’ll get a whole list of all methods.

if you expected rather more context relevant tips, feel free to repost your code after applying the points from above :slight_smile:

have a nice day

Unnecessary parentheses, and I’d use a space (better readability):

if buttons & 16:

How about this:

                for key, val in self.KeyPosDic.items():
                    Dist.append(self.PosVec - val)
                    DistL.append(Dist[-1].length())

Actually, you don’t even need to call items() there, you can just iterate through values(), because you don’t need the keys.

Use spaces for better readability:

                    self.KeyPosM = loader.loadModel("models/BallSmall")
                    self.KeyPosM.setShaderInput("texDisable", 1, 1, 1, 1)