Python 3 类型提示无? [英] Python 3 type hinting for None?

查看:49
本文介绍了Python 3 类型提示无?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I'm trying to set a type hint in Python in a function, you can add more than one type hint with something: str|bool='default value', but, what are the type hinting for None? :/

推荐答案

从你的例子:

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

我注意到您的用例是某事或无".

I've noticed that your use case is "something or None".

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

Since version 3.5, Python supports type annotations via typing module. And in your case, the recommended way of annotating is by using typing.Optional[something] hint. This has exact meaning you're looking for.

因此 another_string_or_None 的提示是:

import typing

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

这篇关于Python 3 类型提示无?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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