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


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

Re: removing nested iffs

Started byPeter Otten <__peter__@web.de>
First post2011-07-29 22:42 +0200
Last post2011-07-29 22:42 +0200
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 Peter Otten <__peter__@web.de> - 2011-07-29 22:42 +0200

#10545 — Re: removing nested iffs

FromPeter Otten <__peter__@web.de>
Date2011-07-29 22:42 +0200
SubjectRe: removing nested iffs
Message-ID<mailman.1632.1311972191.1164.python-list@python.org>
Josh Benner 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?
> 
> def format_rsync_src_string(args, server="RSYNC"):
>     """ Format an rsync source directory string. """
>     if args.server is None:
>         raise CopyNightlyError("No rsync server provided.")
>     src = "{0}::".format(args.server)
>     if args.project not None:
>         src += "{0}/".format(args.project)
>         if args.version not None:
>                 src += "{0}/".format(args.version)
>                 if args.build not None:
>                     src += "Build {0}".format(args.build)
>     return src

How about 

def format_pairs(pairs):
    for template, value in pairs:
        if value is None:
            break
        yield template.format(value)

def format_rsync_src_string(args, server="RSYNC"):
    """ Format an rsync source directory string. """
    if args.server is None:
        raise CopyNightlyError("No rsync server provided.")

    return "".join(format_pairs([
        ("{0}::", args.server),
        ("{0}/", args.project),
        ("{0}/", args.version),
        ("Build {0}", args.build)]))

[toc] | [standalone]


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


csiph-web