python / python/mypy

Odd behavior when creating namedtuple

Open
#10,954 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic-error-reporting topic-named-tuple topic-usability
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I am writing a descriptor and attempting to annotate using the typing module. I think I have found a bug, but since I am pretty new to mypy I am posting it here. Below is the behavior I encountered:

# test_file.py
from collections import namedtuple

class Snapshot:
    def create_tuple_type(self, name: str):
        self.tuple_type = namedtuple(name, [])  # line 6

def create_tuple_type_1(name: str):
    x = namedtuple(name, [])                    # line 9

def create_tuple_type_2(name: str):
    return namedtuple(name, [])

running: mypy test_file.py prints:

snapshot\tinutest.py:6: error: NamedTuple type as an attribute is not supported
snapshot\tinutest.py:6: error: namedtuple() expects a string literal as the first argument
snapshot\tinutest.py:9: error: namedtuple() expects a string literal as the first argument
Found 3 errors in 1 file (checked 1 source file)

I am confused:

  • what does the first error mean, I am not using NamedTuple (also NamedTuple is not a type, but a function)?
  • I explicitly set name to be a string, why the second and third error (it says 'literal', but there is no reason this would not work, it actually does in practice ;-)?
  • why does create_tuple_type_1 give an error, while create_tuple_type_2 doesn't?

This might more issues, but since they occur so close together, they might be correlated?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The reproducer is the inline test_file.py example; start by running mypy against it and comparing the diagnostics for the attribute assignment, local assignment, and return cases. Trace the handling of namedtuple calls and annotated attributes, then define done as consistent, documented behavior or corrected diagnostics for all three examples.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.