没有Python 3类型提示?

标签 python python-3.x nonetype type-hinting

def foo(
        hello: str='world', bar: str=None,
        another_string_or_None: str|????=None):
    pass

我正在尝试在 Python 中的函数中设置类型提示,您可以使用 something: str|bool='default value' 添加多个类型提示,但是,什么是None 的类型提示? :/

最佳答案

从你的例子:

def foo(
        hello: str='world', bar: str=None,
        another_string_or_None: str|????=None):
    ...

我注意到您的用例是“某物或无”。

从 3.5 版开始,Python 通过 typing module 支持类型注释. 在您的情况下,推荐的注释方式是使用 typing.Optional[something] hint .这具有您正在寻找的确切含义。

因此 another_string_or_None 的提示将是:

import typing

def foo(
        hello: str='world', bar: str=None,
        another_string_or_None: typing.Optional[str]=None):
    ...

关于没有Python 3类型提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19202633/

相关文章:

python 嵌套 for 循环 zip

python - 当我将变量写入文本文件时,为什么会得到 'none'

python - 在每列中查找 DataFrame 中不同元素的计数

python - 使用 pd.series 为多列评估和提取字段

python - Python 3 中的 __phello__ 是什么?

python - if条件下没有,如何处理缺失数据?

python - 在 Python 中,None 是唯一对象吗?

python - 如何查找模型是否是从 Django Admin 或其他地方保存的

python - django 使用原始 mysql 进行搜索

python-3.x - Python CV2 按键响应时间慢