Incorrect line number of wrong symbol name inside f-strings

Bug #1666811 reported by Lele Gaifax
12
This bug affects 2 people
Affects Status Importance Assigned to Milestone
Pyflakes
Confirmed
Undecided
Unassigned

Bug Description

All errors related to undefined symbols used within f-strings are reported with an incorrect line number of "1".

The following snippet

print('Foo')
print(f'{a}')

reports

p.py:1: undefined name 'a'

whereas the error appears on line 2.

Ian Cordasco (icordasc)
Changed in pyflakes:
status: New → Confirmed
Revision history for this message
Oscar Campos (oscar-campos) wrote :

This is not a problem in PyFlakes but in the formatted literals implementation in the core of CPython itself. The AST child Name node for the formatting variables reports 1 as both line and column as the nodes are generated by PyParser_ASTFromString "automagically" in fstring_find_expr (Python/pythoinrun.c and Python/ast.c respectively).

I don't see how this should/could be fixed by PyFlakes

Revision history for this message
Lele Gaifax (lelegaifax) wrote :

Sadly this is true, the Name elements of an fstring carry an useless lineno, as the following script demonstrates:

from ast import FormattedValue, Str, parse

code = """\
a = 1
b = f"a={a} c={c}"
"""

parsed = parse(code)
first, second = parsed.body
bvalue = second.value

print(type(bvalue))

for n in bvalue.values:
    print(type(n))
    if isinstance(n, Str):
        print("%d:%d %r" % (n.lineno, n.col_offset, n.s))
    else:
        assert isinstance(n, FormattedValue)
        print("%d:%d" % (n.lineno, n.col_offset))
        v = n.value
        print(type(v))
        print(" %d:%d %r" % (v.lineno, v.col_offset, v.id))

that emits:

<class '_ast.JoinedStr'>
<class '_ast.Str'>
2:4 'a='
<class '_ast.FormattedValue'>
2:4
<class '_ast.Name'>
  1:1 'a'
<class '_ast.Str'>
2:4 ' c='
<class '_ast.FormattedValue'>
2:4
<class '_ast.Name'>
  1:1 'c'

However, couldn't PyFlakes recognize those Name elements and go up to the enclosing FormattedValue and use its position as the error location?

Revision history for this message
Lele Gaifax (lelegaifax) wrote :

FYI, this is solved in Python 3.6.3, yay!

To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.