Skip to content

namedtuple does not accept f strings as string literal for the first arg #9046

Closed
@cy

Description

@cy

When creating a namedtuple, if the first argument is an f string, mypy throws main.py:3: error: namedtuple() expects a string literal as the first argument

In https://mypy-play.net/?mypy=latest&python=3.8

from collections import namedtuple
a = "b"
test = namedtuple(f"{a}", ["a"])

throws

main.py:3: error: namedtuple() expects a string literal as the first argument
Found 1 error in 1 file (checked 1 source file)

Interestingly, if string interpolation is not used inside the fstring, then mypy does not complain:

from collections import namedtuple
test = namedtuple(f"b", ["a"])

returns

Success: no issues found in 1 source file

As https://www.python.org/dev/peps/pep-0498/ considers fstrings string literals, I'd expect fstrings to be accepted as the first arg to namedtuple.

I suspect this bug is caused by this line

if not isinstance(args[0], (StrExpr, BytesExpr, UnicodeExpr)):
where an fstring is surprisingly not a StrExpr, BytesExpr or UnicodeExpr:
(ipython)

In [1]: b = "a"

In [2]: a = f"{b}"

In [8]: from mypy.nodes import (StrExpr, BytesExpr, UnicodeExpr)

In [10]: any(isinstance(a, expr) for expr in [StrExpr, BytesExpr, UnicodeExpr])
Out[10]: False

Locally I am using mypy 0.770 and python 3.8; but in mypy-play.net I observe the same thing happening on mypy latest.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions