Inline assignments

Fredrik Tolf fredrik at
Sun Mar 5 15:09:28 CET 2006

Hi list!

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

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

Another common problem for me are while loops. I would often like to do
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
while True:
	pos = somestring.find("/")
	if pos == -1: break
	# ...

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

How would you go about these situations?

Thanks for your time!

Fredrik Tolf

More information about the Python-list mailing list