打开 Path 对象时的 Pycharm 类型提示警告

san*_*ers 9 python type-hinting pycharm

使用以下代码:

from pathlib import Path

file = Path("test.txt")

with open(file) as fl:
    pass 
Run Code Online (Sandbox Code Playgroud)

Pycharm 给出以下警告 file

Unexpected type(s): (Path) 

Possible types: 
  (Union[str, bytes, int]) 
  (Union[str, bytes, int, PathLike]) less... (Ctrl+F1) 

Inspection info: This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Types of function parameters can be specified in docstrings or in Python 3 function annotations.
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么 ?

小智 -3

你可以这样使用它

    file = "test.txt"

    with open(file) as fl:
        pass 
Run Code Online (Sandbox Code Playgroud)
  • Pycharm 甚至会提示您可能想要使用的文件。我这样使用没有任何问题。
  • 如果您要查找的文件与代码不在同一目录中,则需要添加完整路径