Is this a "gotcha" in Python?

Skip Montanaro skip.montanaro at gmail.com
Mon Apr 22 18:20:36 EDT 2019


> 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. The assignment to _up is flagged though. 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.)

So, it's improving.

Skip


More information about the Python-list mailing list