Invoking return through a function?

Steve D'Aprano steve+python at pearwood.info
Sun Oct 29 20:58:11 EDT 2017


On Mon, 30 Oct 2017 06:09 am, Alberto Riva wrote:

> But that's exactly why I would like to be able to use macros. I think
> that being able to write "return if this happens" is much more explicit
> than having to write the full if statement, every time.

There have been proposals in the past for syntax similar to

    return value if condition

as a short-hand for

    if condition: return value

but since the only thing actually saved is a colon (or, at worst, a colon, a
newline and an indent) they went nowhere.

Sometimes the (hypothetical) gain in readability is outweighed by the increase
in unwanted language/syntactic complexity.


> The idea is that 
> you abstract a pattern giving it a name, so every time you see that name
> you know immediately what's going to happen, without having to decode
> the conditional in your mind.

Too much of a good thing... 

That's fine for when you are writing the code the first time. You see a
pattern, you give it a name, and you use that name over and over again.

But when you come back to maintain the code in five years time, you have
forgotten the name and the pattern. You see the name, not the pattern,
because you're only focusing on a small part of the code.[1] What does the
mystery name do? Unless you are very lucky and the function is very well
named[2], you have to dig back through a chain of functions and macros to
work it out.

If the pattern was small and simple enough (like the example in this
thread, "if key not in dict: return") having to dig back through its chain of
functions and macros is more costly and difficult.

Having too many named concepts to understand is as big a cognitive burden as
having too few.







[1] Software maintenance is harder, less rewarding and simply less fun than
writing code in the first place.

[2] There are only two hard problems in computer science: cache invalidation,
and naming things.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list