Do pythons like sugar?

Max M maxm at mxm.dk
Thu Jan 9 05:05:07 EST 2003


Afanasiy wrote:
> I've written this method for a text formatting class...
> But it's ugly as sin. With all those self's I consider
> it much less readable than it could be...
> 
> A few languages provide syntax sugar for dealing with
> this by allowing you to localize the class scope.
> 
> Does Python? eg. `with self do:`
> 
>   def format( self, width=80 ):    
>     self.lines = ['']
>     i = 0
>     for word in self.text.split():  
>       if self.textwidth(self.lines[i]) + self.textwidth(word) <= width:
>         if self.textwidth(self.lines[i]) > 0:
>           self.lines[i] += ' '
>         self.lines[i] += word
>       else:
>         i += 1
>         self.lines.append(word)


No. But a little imagination takes you a long part of the way:

def format( self, width=80 ):
     twidth = self.textwidth
     lines = ['']
     i = 0
     for word in self.text.split():
         if twidth(lines[i]) + twidth(word) <= width:
             if twidth(lines[i]) > 0:
                 lines[i] += ' '
             lines[i] += word
         else:
             i += 1
             lines.append(word)
     self.lines = lines

regards Max M

-- 

hilsen/regards Max M

http://www.futureport.dk/
Fremtiden, videnskab, skeptiscisme og transhumanisme





More information about the Python-list mailing list