代码之家  ›  专栏  ›  技术社区  ›  576i

Python:如何在函数中键入提示文件名?

  •  1
  • 576i  · 技术社区  · 7 年前

    Python中提示文件名的最佳方式是什么, 这样就可以将任何东西传递到一个可以作为文件打开的函数中了?

    尤其是通过Pathlib找到的字符串和文件。

    def myfunc(filename: str) -> None:
        with open(filename) as f1:
            # do something here
    
    1 回复  |  直到 6 年前
        1
  •  25
  •   Aran-Fey Kevin    6 年前

    我认为您正在寻找的是结构类型,它还不受支持。这项建议载于 PEP 544

    同时,您可以通过使用注释来完成一半的工作 Union[str, bytes, os.PathLike] .

        2
  •  10
  •   Eric Langlois    6 年前

    PEP 519 typing.Union[str, bytes, os.PathLike]

        3
  •  3
  •   Remmar00    5 年前

    正如埃里克所说,

    PEP 519 建议使用 typing.Union[str, bytes, os.PathLike]

    但你也应该考虑 _typeshed.AnyPath :支持不同版本的各种路径,是内置库中文件名的默认输入提示,如 the function open() itself 导入它会导致类型帮助器识别输入应该是文件名,并且可能有助于类型提示路径。它也有变化 _typeshed.StrPath _typeshed.BytesPath Here for their definition .

    但是,您不能只导入 typeshed 模块,作为 it doesn't exist at runtime

    from typing import TYPE_CHECKING
    AnyPath = None
    if TYPE_CHECKING:
        from _typeshed import AnyPath
    

    最后,在当前的3.10测试版中, AnyPath has been renamed to StrOrBytesPath ,以便将字符串和bytestring从路径模块的路径中分离出来,不久将不会看到另一个AnyPath。因此,如果您计划只输入str文件名,可以使用 _typeshed.StrPath ,或者干脆放弃使用 键入.Union[str,bytes,os.PathLike]