Inline assignments

Peter Hansen peter at engcorp.com
Sun Mar 5 10:14:10 EST 2006


Fredrik Tolf wrote:
> I'm relatively new to Python, and one thing I can't seem to get over is
> the lack of in-expression assignments, as present in many other
> languages. I'd really like to know how Python regulars solve the
> problems posed by that.
> 
> For example, I recently wanted to do this:
> 
> if callable(f = getattr(self, "cmd_" + name)):
> 	# Do something with f
> elif callable(f = getattr(self, "cmdv_" + name)):
> 	# Do something else with f

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

(and note that the "if callable(f)" test is probably not required 
anyway, though that depends on the specific case)

If the "do something" and "do something else" parts are really doing 
different things, then you should put that code into other methods and 
include references to those methods in the list along with the prefixes, 
so you can keep the code free of the extra layer of logic.  A more real 
example would be useful in continuing the discussion down that path. 
(At the moment, the answer to that looks like it would be "since you are 
already looking up a callable, just call it".)

> 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
> 
> However, that, too, is impossible, and I end up doing something like
> this:
> while True:
> 	pos = somestring.find("/")
> 	if pos == -1: break
> 	# ...
> 
> Which is quite ugly. 

Ugly is very much in the eye of the beholder.  In this case, with an eye 
to readability and maintainability, I find the latter much more direct 
than the former, which blends a search, and assignment, a comparison, 
and a conditional control structure all into a single line, making it 
very hard to just scan the code quickly and know for sure what is happening.

 > This might have been a bad example, since
> somestring.split() could be used instead, but it's still valid for other
> situations.

And each of those other situations usually has an equally 
straightforward solution. :-)

-Peter




More information about the Python-list mailing list