if/elif chain with assignment expressions

David Fraser davidf at sjsoft.com
Tue Jul 13 03:46:44 EDT 2004


John Roth wrote:
> "Paul Rubin" <http://phr.cx@NOSPAM.invalid> wrote in message
> news:7x4qoe6vae.fsf at ruckus.brouhaha.com...
> 
>>steve holden <sholden at holdenweb.com> writes:
>>
>>>Indeed, you  might think so. But this topic has been discussed
>>>exhaustively (which isn't to say you aren't about to hear a lot more
>>>about the subject) in this group, and the assignment operation is
>>>*not* an operator for specific reasons the FAQ attempts to make clear
>>>in
>>>
> 
> http://www.python.org/doc/faq/general.html#why-can-t-i-use-an-assignment-in-an-expression
> 
>>Yeah, I've seen those discussions before.  The if/elif/elif example was
>>something I hadn't seen in those discussions, and it came up in some
>>code I was writing yesterday, so I posted about it.
> 
> 
> I thoroughly agree. I've come up with that any number
> of times, and allowing an assignment in an expression
> is one of the things that I think should be done.
> 
> Note that I don't really care about the syntax, and
> I care even less if it's really intuitive to novices. It's
> one of those things that leads to simpler, more expressive
> code when you need it, but it's not something that's
> absolutely necessary to hack together a working
> program while you're learning the language.
> 
> The use case is an expression in an if statement, not
> an expression in a while statement. The latter can
> be handled with an iterator and a for statement,
> which might be a good idea, and it might not depending
> on the specific situation.
> 
> There is an alternative, which is to find all of the
> cases where this is likely to be a problem, and fix
> the calls so that they naturally return an iterator.
> 
> To make this specific, let's take a look at the
> <string>.find and <string>.rfind. This method
> pair is probably the poster child of how not to
> do it in a pythonic manner.
> 
> Let's assume we had a <string>.findall()
> method, defined to return a list of all
> indexes of the first character of each
> substring that matches the given string.
> 
> Then we could say something like:
> 
> for firstMatch in myString.findall("fubar")[:1]:
>    do something with it
> 
> While this is not exactly obvious to the novice,
> it not only gets the job done, but the findall()
> method also has a number of other very
> nice properties. It behaves properly in a boolean
> context, and it never returns an incorrect index
> (that is, -1.)
> 
> If you really did want to process all matches,
> it's even easier.

I support str.findall ! Yes! Please!

David



More information about the Python-list mailing list