python - Error from Pycharm: Expected type 'SupportsIndex | slice', got 'str' instead - Stack Ov

My input file, infile is as follows:NUMBER,SYMBOL1,AAPL2,MSFT3,NVDAHere is my code:import csvinfil

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?

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?

Share Improve this question edited Mar 10 at 16:58 Daraan 4,2427 gold badges22 silver badges47 bronze badges asked Mar 10 at 16:44 Charles KnellCharles Knell 6434 silver badges16 bronze badges 5
  • 2 Looks a bit like a bug/wrong type-inference, row should be a dict, the error indicates that row is inferred as a list. – Daraan Commented Mar 10 at 16:56
  • 2 What version of PyCharm? Looks like this bug which was supposedly fixed. But there are comments as recent as 6 months ago saying it's still happening. – Barmar Commented Mar 10 at 17:12
  • When I run this code, I'm not getting any errors. @Barmar might be right, this might be a bug in an older version – ServerS Commented Mar 10 at 17:13
  • 2 @ServerS It's not an error you get when running the code, just in PyCharm's type hints. – Barmar Commented Mar 10 at 17:13
  • Comparing linter output from multiple tools, including pyright and mypy —strict, is always a fun game. – J_H Commented Mar 10 at 19:43
Add a comment  | 

1 Answer 1

Reset to default 0

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)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744834344a4596173.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信