Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #10547 > unrolled thread

Re: removing nested iffs

Started byChris Angelico <rosuav@gmail.com>
First post2011-07-30 06:47 +1000
Last post2011-07-30 06:47 +1000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: removing nested iffs Chris Angelico <rosuav@gmail.com> - 2011-07-30 06:47 +1000

#10547 — Re: removing nested iffs

FromChris Angelico <rosuav@gmail.com>
Date2011-07-30 06:47 +1000
SubjectRe: removing nested iffs
Message-ID<mailman.1634.1311972429.1164.python-list@python.org>
On Sat, Jul 30, 2011 at 5:40 AM, Josh Benner <sjbenner@gmail.com> wrote:
> I'm writing a function to create a string that gets longer iff an argument
> is defined.  In there a more elegant way than nesting all those ifs?

Your logic appears to be: Proceed along a specified list and stop when
you find that you don't have the corresponding information (meaning
that args.build will be ignored if args.project==None). I'd do that
with multiple return statements:

src = args.server + "::"
if not args.project: return src
src += args.project + "/"
if not args.version: return src
# etc

Note that I'm converting to bool ("if not blah") instead of explicitly
checking for None. If an empty string is a valid
project/version/build, change this back to the "is not None" syntax.

I wouldn't bother with format() when it's simply putting a string on
one side or the other of something; simpler just to add two strings
together (and probably faster, but profile before you pick based on
that).

On the other hand, if your if statements are the unusual case and
maybe an error, it might be easier to do this:

try:
 src = args.server + "::"
 src += args.project + "/"
 src += args.version + "/"
 src += "Build " + args.build
except TypeError:
 pass
return src

Attempting to concatenate None to a string raises TypeError "Can't
convert 'NoneType' object to str implicitly" on my Python 3.2, and on
Python 2.4 and 2.6, a TypeError "cannot concatenate 'str' and
'NoneType' objects". Check what your version does. In any case, the
above try/except will bail out without error when it gets a TypeError
of any sort, so be sure this won't be a problem to you!

Chris Angelico

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web