如何在函数中键入提示文件名? [英] How do I type hint a filename in a function?

查看:78
本文介绍了如何在函数中键入提示文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中提示文件名的最佳方式是什么?以便将任何内容传递给您可以作为文件打开的函数?

What is a best way in Python to hint a filename, so that it's acceptable to pass anything into a function that you can open as a file?

特别是通过 Pathlib 找到的字符串和文件.

Especially both strings and files found via Pathlib.

def myfunc(filename: str) -> None:
    with open(filename) as f1:
        # do something here

推荐答案

我认为您正在寻找的是结构类型,目前尚不支持.它在 PEP 544 中提出.

I think what you are looking for is Structural Typing, which is not yet supported. It is proposed in PEP 544.

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

In the mean time, you could do a half-way effort by annotating with Union[str, bytes, os.PathLike].

这篇关于如何在函数中键入提示文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆