pythonpycharmpython-typing

Error from Pycharm: Expected type 'SupportsIndex | slice', got 'str' instead


My input file, infile is as follows:

NUMBER,SYMBOL
1,AAPL
2,MSFT
3,NVDA

Here is my code:

import csv

infile = "stock-symbols-nasdaq-SO.csv"

with open(infile, encoding='utf-8') as csvfile:
    reader = csv.DictReader(csvfile)  # Read CSV as a dictionary
    for row in reader:
        print(row)
        symbol = row['SYMBOL']  # Error from Pycharm: Expected type 'SupportsIndex | slice', got 'str' instead
        print(symbol)

This code "appears" to run correctly, but why is Pycharm indicating an error? Is their anything that I can do to remove it?


Solution

  • A solution to this is to use a type hint for row as follows:

    with open(infile, encoding='utf-8') as csvfile:
        reader = csv.DictReader(csvfile)  # Read CSV as a dictionary
        for row in reader:
            print(row)
            row: dict[str, str]  # type hint which specifies that row is a dict with string keys and values
            symbol = row['SYMBOL']
            print(symbol)