0

I define a NamedTuple as follow to get data scraped from a webpage (grades from a restaurant rating website):

class Grades(NamedTuple):

    Value: Optional[int] = None
    Price: Optional[int] = None
    Service: Optional[int] = None
    Taste: Optional[int] = None

I then assign the values by index with a loop instead of using the keys as I get the grades as a list of integers with the same order (Value, Price, Service, Taste).

scraped_grades = Grades()
for i, subject in enumerate(data):
    scraped_grades[i] = data

Yet when running mypy I get the following error:

Unsupported target for indexed assignment

I was under the impression that numerical indexes were a valid way to access or assign data in a NamedTuple. Thinking that this may simply not be supported by mypy, I tried to assign the values using keys instead, which may be more orthodox:

for i, key in enumerate(scraped_grades ._fields):
    scraped_grades[key] = data[i]

But this gives me the exact same error.

Does mypy not support NamedTuples at all? I know I could also just #type: ignore for this specific line, but I'd prefer a proper solution if one exists (or at least an explanation of why this fails).

bad_coder
  • 11,289
  • 20
  • 44
  • 72
user2969402
  • 1,221
  • 3
  • 16
  • 26
  • 1
    No, `mypy` is **correctly** identifying an error, named tuples **are `tuple`** objects, and `tuple` objects are immutable, and *don't support item assignment*. If you ran this code, it would generate a runtime error, namely, something to the effect of `TypeError: 'Grades' object does not support item assignment` Note, named tuples do not have "keys" either... "I was under the impression that numerical indexes were a valid way to access or assign data in a NamedTuple" I don't know *where* you got that impression, but two seconds in a REPL would have shown you that is incorrect... – juanpa.arrivillaga May 24 '20 at 10:16
  • Indeed, how stupid of me. I fixed it with `scraped_grades = Grades(*data)` – user2969402 May 24 '20 at 10:20
  • Note also, *named tuples do not have keys* they have attributes. So `grade['Value']` would give you an error. You'd need to use `grade.Value`. Although, you should stick to PEP8 conventions, and use lower-case attribute names. – juanpa.arrivillaga May 24 '20 at 10:20

0 Answers0