Is this a "gotcha" in Python?

Chris Angelico rosuav at gmail.com
Mon Apr 22 18:27:28 EDT 2019


On Tue, Apr 23, 2019 at 8:21 AM Skip Montanaro <skip.montanaro at gmail.com> wrote:
>
> > Interesting. So it would flag this code?
> >
> > for _ in range(5): next(f) # skip five lines
>
> As of at least recent versions (I have 2.1.1 in my Conda install at
> home) It seems to properly accept "_" as a variable name, even when
> not used. It also seems to accept any variable name as a loop index.
> Here's a silly function which demonstrates current behavior:
>
> def skipper(filename):
>     f = open(filename)
>     _ = filename.lower()
>     _up = filename.upper()
>     filename.title()
>     for i in range(5):
>         next(f)
>     return f
>
> The assignment to "_" is accepted, as is the use of "i" as the loop
> variable.

By "accepted" you mean that it isn't complaining? Good; although I'm
not sure why you'd use "_" in a simple assignment context. Clearly
it's quite happy to have *any* unused variable as a loop iterator, and
honestly, I think that's probably correct (since not everyone uses the
underscore convention).

> The assignment to _up is flagged though.

What kind of flagging? "Unused variable", or is it saying that "_up"
is an unconventional name for a local (and perhaps should have been
declared global)?

> It also doesn't
> complain about the ignored return value for filename.title(). (In all
> fairness, I don't think pyflakes was ever held up as a "deep" analyzer
> of Python source, so couldn't be expected to know that string's title
> method operates without side effect.)

Yeah, that one's a bit harder to flag. I wouldn't fault any linter for
not knowing that something's useless in that way. Would be cool if it
knew, but no big deal if it doesn't.

ChrisA



More information about the Python-list mailing list