For review: PEP 308 - If-then-else expression

Paul Rubin phr-n2003b at NOSPAMnightsong.com
Sat Feb 8 21:16:45 CET 2003


Michael Hudson <mwh at python.net> writes:
> An example:
> 
>     def get_arg(self, default=1):
>         """Return any prefix argument that the user has supplied,
>         returning `default' if there is None.  `default' defaults
>         (groan) to 1."""
>         if self.arg is None:
>             return default
>         else:
>             return self.arg
> 
> could become
> 
>     def get_arg(self, default=1):
>         """Return any prefix argument that the user has supplied,
>         returning `default' if there is None.  `default' defaults
>         (groan) to 1."""
>         return default if self.arg is None else self.arg
>
> Is that an improvement?  *I* certainly don't think so.  The original
> has all these wonderful visual cues about what's going on (colons at
> end of lines and indentation being the key two).  The second just has
> a stream of name-like tokens.  It looks better when syntax hilighted,
> but only slightly.

Think of how you actually call get_arg:

    a = x.get_arg()

In order to read that line you have to actually go check the
definition of get_arg.  The conditional expression (maybe) simplifies
your code, not by shortening the get_arg function, but by eliminating
it.  You'd instead say

   a = self.arg if (self.arg is not None) else 1

or whatever.  Maybe that syntax is clumsy but it still seems
preferable to having to scroll to some method definition several
screens away in order to find a 4-line function definition
that needs 3 lines of documentation to explain what it's doing.




More information about the Python-list mailing list