removing nested iffs

Chris Angelico rosuav at gmail.com
Fri Jul 29 16:47:05 EDT 2011


On Sat, Jul 30, 2011 at 5:40 AM, Josh Benner <sjbenner at 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



More information about the Python-list mailing list