RFC: For Loop Invariants

Chris Angelico rosuav at gmail.com
Fri Apr 10 20:50:53 EDT 2020


On Sat, Apr 11, 2020 at 10:32 AM Juergen Brendel <juergen at brendel.com> wrote:
>
>
> Hello!
>
> On Fri, 2020-04-10 at 15:44 -0500, Elliott Dehnbostel wrote:
> > chars = "abcaaabkjzhbjacvb"
> > seek = {'a','b','c'}
> > count = 0
> >
> > for a in chars if a in seek: count += 1
>
> Interesting proposal. However, I'm not sure how much benefit it really
> will give us in practice. Reason being: Conditions are often not
> trivial, descriptive variable names are often not super short. Before
> you know it, the expressions for the iterable and for the condition are
> long enough to go past your project's max line-width.

Corollary: Conditions ARE often quite simple, and descriptive variable
names used in short-scope situations (such as loops) ARE often fairly
short.

for var in dir(config):
    if var.startswith("__"): continue # Ignore dunders

for part in tweet:
    if not part: continue

for id, timer in database.list_timers(channelid):
    if id in timer_sockets:
        for ws in timer_sockets[id]:
            ws.send(json.dumps({"type": "adjust", "delta": delta}))

for setup in data["setups"]:
    if setup == "": continue # The shim at the end

These were all taken from one project of mine - this is production
code. The conditions are simple enough and the loops have descriptive
but not overly-long names. In the case of the timers example, I could
word it with timer_sockets.get(id, ()), but the others all would
benefit from this proposal.

It's easy to show loops that come close to 80 characters and
conditions that add as much again, but real code isn't always that
messy.

ChrisA


More information about the Python-list mailing list