Inline assignments

Duncan Booth duncan.booth at invalid.invalid
Sun Mar 5 16:25:04 CET 2006


Fredrik Tolf wrote:
> However, since I can't do that in Python, I ended up using an extra
> local variable instead, like this:
> 
> f = getattr(self, "cmd_" + name)
> f2 = getattr(self, "cmdv_" + name)
> if callable(f):
>      # Do something with f
> elif callable(f2):
>      # Do something with f2

If 'do something' is the same thing:

for prefix in ('cmd_', 'cmdv_'):
   f = getattr(self, prefix+name)
   if callable(f):
      # do something with f
      break

If 'do something' is different each time, put each block into a method:

   def do_cmd(self, f): ...
   def do_cmdv(self, f): ...

...
for prefix, action in (('cmd_', self.do_cmd), ('cmdv_', self.do_cmdv)):
   f = getattr(self, prefix+name)
   if callable(f):
      action(f)
      break

> 
> Another common problem for me are while loops. I would often like to do
> this:
> while (pos = somestring.find("/")) != -1:
>      part = somestring[:pos]
>      somestring = somestring[pos + 1:]
>      # Handle part

for part in somestring.split("/")[:-1]:
    # handle part

Are you sure you didn't want to process the last part of the string as 
well? I would have thought that to be more common, and rather harder to 
write using your original structure.

> 
> Which is quite ugly. This might have been a bad example, since
> somestring.split() could be used instead, but it's still valid for other
> situations.
> 
Not really. Your original loop refactors quite nicely by calling a method 
or function which returns a sequence of results. The same pattern in will 
always be refactorable in the same way. If the appropriate 'split' function 
doesn't already exist then you can write it.

A very common way to rewrite this sort of loop these days is to write a 
generator. It is usually beneficial to factor out the complex part of the 
loop logic in this way as then you only have to write it once no matter how 
many loops you have with the same structure.



More information about the Python-list mailing list